#### Archived

This topic is now archived and is closed to further replies.

# Global variables in multi-source program

This topic is 6254 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

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.

##### Share on other sites
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.

##### Share on other sites
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)

##### Share on other sites
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.

##### Share on other sites
Thanks guys, now it links and executes like a dream.

1. 1
Rutin
49
2. 2
3. 3
4. 4
5. 5
JoeJ
19

• 11
• 16
• 9
• 10
• 13
• ### Forum Statistics

• Total Topics
633003
• Total Posts
3009846
• ### Who's Online (See full list)

There are no registered users currently online

×