Global variables in multi-source program

Started by
3 comments, last by core 22 years, 7 months ago
I have a question regarding a recent problem I''ve encountered when making a gradual transition from programming in C to C++. To illustrate my problem I created a couple source files (.c) and one header file. In the header file I have a single global variable ( int x; ). Both source files include my header file. When I compile and link, there are no errors. However, as soon as I change the file extensions from .c to .cpp (I''m using VC++) and try to compile and link the EXACT same, unmodified code, the linker throws an error about the global variable being multiply defined. It''s most likely something elementary that I''ve overlooked or haven''t learned. Help is greatly appreciated.
Advertisement
Two possible solutions:
1. Declare the variable external in each of your implementation (.cpp) files:
extern var_type var_name;// e.g. extern int variable; 


2. Ensure the header file is never included multiple times (the better solution):
#ifndef _IDENTIFIER#define _IDENTIFIER// .. contents of header file#endif // _IDENTIFIER 

This makes sure redundant inclusion of this file doesn''t occure, because the declarations have already been seen by the compiler (why show them to it twice?) Usually, the IDENTIFIER is a version of the file name. If the header file is MyHeader.h, a good identifier is _MYHEADER_H.

Hope this clarifies things for you a bit.
What you need is actually a combination of the two things that Oluseyi mentioned and one more step.

First, in the header file, add the extern keyword. So, if your global is an integer x, you put
extern int x;

Next, if you haven''t already, make sure that your header files are guarded from multiple inclusions by ifndef''s (I''m assuming you''re doing this already).

Last, make sure that in one (only one) CPP file, you declare x as just:
int x;
You can even initialize it here, so you can put:
int x = 10;

There is one caveat. Global variables are not constructed in any specific order, so you shouldn''t use the global x to initialize another global. Globals should be considered unitialized until you begin to execute code in main() (or WinMain() as the case may be)
fyi, the reason it works in C and not C++ is that C++ is much more strict about the rules than C is. Many things that are warnings in C compilers are errors in C++ compilers.
Thanks guys, now it links and executes like a dream.

This topic is closed to new replies.

Advertisement