Reputation: 2811
I'm using C and this is what I'm doing to instantiate a global C string
In the header of a single file
const char SINGLE_MSG[] = "single msg";
In the headers of all other files
extern const char SINGLE_MSG[];
It always works fine when compiling in C mode, but seems to create binder errors when compiling in C++ mode. Here is an example of such errors:
pksw_nd_proc_test2.dev32.i0.pr.obj : error LNK2001: unresolved external symbol "char const * const SINGLE_MSG" (?SINGLE_MSG@@3QBDB)
I've seen a similar question where they also specify the buffer length. I'd rather not, since if don't want to have to remember changing that if I decide to change the string value in the source. That's the whole point to make this global, so every instance sees the same value.
Am I doing something wrong?
Since it's a constant, would it be better to make it static as well? It would be fine for me to have extra copies of it, as long as I don't have to copy the string value manually in the source to do the initialization.
Edit: please note that I'm using a program that I don't fully control. It's a network simulator that lets me define a "header block" for each node. I do not have any way to explicitly include the header of a node in the header of another node.
That's why I was using extern in C, and the different way globals work between the 2 languages is probably the reason I get the linker errors.
According to the answers, the solution is to make a new, separate header file containing the definitions of the global variables and include that in all other headers.
Upvotes: 1
Views: 3939
Reputation: 560
When you create a global constant variable in the header, then that variable never actually gets committed to memory.
What happens instead is that any code that uses that variable simply replaces any reference with "single msg".
This means there is no need use extern, but in turn does mean you must always include that header if you use the variable.
What extern is actually used for is exposing a variable that has been declared in a .cpp file, and therefore is in memory somewhere, to other cpp files. This is only necessary if you want a global but dynamic variable.
Upvotes: 1