Discussion:
Includefiles with initialised variables?
(too old to reply)
Joerg Toellner
2003-07-16 09:49:59 UTC
Permalink
Hi Group,

Dont know how to solve my problem with my little brain by myself. Maybe my
way is not the best at all and maybe not C++ style...but i don't no to do
better at the moment. So excuse my maybe horrible coding-style.

I have the following files:

a.cpp
b.cpp
b.h

in b.h are many declarations and function prototypes that have to be used in
a.cpp AND b.cpp. So i have to include b.h in both .cpp files.

As there are initialised variables in the .h files too, like:

char error_msgs[][100] = { "No error",
"I/O error",
"Too many fingers on
keyboard error",
"Out of this world error"
};

i decided to wrap the .h file with the lines:

#if !defined( _B_HFILE_INCLUDED_ )
#define _B_HFILE_INCLUDED_

... blah blah blah // The content of b.h

#endif

to prevent double inclusion of b.h and so the h file should only be
included once.

But although i do this, i get the compilation/linking error:

b.obj: char * error_msgs[][100] already defined in a.obj

Huh? I thought the #if/#endif construction will prevent this.

I really don't want to define all the hundreds of error message strings in
every .cpp file. :-( What do i wrong?

Any hint appreciated.

TIA
Joerg Toellner
Jakob Bieling
2003-07-16 10:18:21 UTC
Permalink
Post by Joerg Toellner
Hi Group,
Dont know how to solve my problem with my little brain by myself. Maybe my
way is not the best at all and maybe not C++ style...but i don't no to do
better at the moment. So excuse my maybe horrible coding-style.
a.cpp
b.cpp
b.h
in b.h are many declarations and function prototypes that have to be used in
a.cpp AND b.cpp. So i have to include b.h in both .cpp files.
char error_msgs[][100] = { "No error",
"I/O error",
"Too many fingers on
keyboard error",
"Out of this world error"
};
#if !defined( _B_HFILE_INCLUDED_ )
#define _B_HFILE_INCLUDED_
... blah blah blah // The content of b.h
#endif
to prevent double inclusion of b.h and so the h file should only be
included once.
b.obj: char * error_msgs[][100] already defined in a.obj
Huh? I thought the #if/#endif construction will prevent this.
No it will not. It will prevent b.h from being included twice in the
same source file. You need to put the variables into one cpp file (maybe
c.cpp) and put the extern counter-parts in a header file (c.h) which you
include in both a.cpp and b.cpp:

-- c.cpp --
char error_msgs[][100] = {
"No error",
"I/O error",
"Too many fingers on keyboard
error",
"Out of this world error"
};
-- end c.cpp --

-- c.h --
extern error_msgs[][100];
-- end c.h --

Then include c.h in a.cpp and b.cpp.

hth
--
jb

(replace y with x if you want to reply by e-mail)

Loading...