I’ve written a simple program in C++ using OpenGL. What I need is to have couple global variables in two files – main.cpp and funcs.cpp – which will hold the same values. When I tried to declare these variables in funcs.h (which is included also in main.cpp) I got this error:
1>main.obj : error LNK2005: "int myVariable" (?myVariable@@3HA) already defined in funcs.obj
1>Path to my program : fatal error LNK1169: one or more multiply defined symbols found
which is quite obvious, because it would create variable in funcs.cpp and main.cpp. When I tried to declare variables this way:
//funcs.cpp
int myVariable;
//main.cpp
int myVariable;
And both of them are global I’m getting exactly the same error as above. What interested me is that both variables are not visible in opposite file, so why it is wrong to have variables with the same name? As far as I know there is no possibility to reference to myVariable in funcs.cpp from main.cpp and reverse. And my second question is – what is the best way to solve my problem, because what I did is just renamed some of these variables (there are many of them) and add functions in funcs.cpp like setNewValue(int newValue) which I can invoke from main.cpp but to be honest – I’m not proud of that.
I use Microsoft Visual Studio 2012, C++/OpenGL.
Using C++:
If you’re trying to share the global variable between the two files, then declare it in one of them, e.g. main.c, just as you’re doing now, and in the other file declare the variable as
extern. This way, the variable has been declared in one file, and the same variable can be used in other files, and you won’t have problems with multiple definitions of that variable.If you want to use a global variable with the same name in each file, such that the files don’t share that variable, then use an anonymous namespace to limit the visibility of the variables:
Standard C: For the sake of completeness, if you’re using standard C, instead of using namespaces to limit the visibility of a variable, you can use the
statickeyword: as above, if you want to use a global variable with the same name in each file, and you don’t want the files to share that variable, then you’ll need to declare them asstatic. This limits their visibility to the current file.Sharing the global using
externworks similarly in C.