This question is not so much a "how to solve" question, but rather a question about why this does not work?
In C ++, I can define a bunch of variables that I want to use for multiple files in several ways.
I can do it like this:
int superGlobal; #include "filethatUsesSuperglobal1.h" int main() {
This method ONLY works if "filethatUsesSuperglobal1.h" has all its implementation there in the header and without an attached .cpp file.
Another way (the "more correct" way) is to use extern:
externvardef.h
#ifndef externvardef_h #define externvardef_h
externvardef.cpp
#include "externvardef.h" int superGlobal;
filethatUsesSuperglobal1.h
#include "externvardef.h" #include <stdio.h> void go();
filethatUsesSuperglobal1.cpp
#include "filethatUsesSuperglobal1.h" void go() { printf("%d\n", superGlobal ); }
main.cpp
#include <stdio.h> #include "externvardef.h" #include "filethatUsesSuperglobal1.h" int main() { printf( "%d\n", superGlobal ) ; go() ; }
This is a small point and a somewhat insignificant question, but Why do I need to declare it extern - should #include be protected on "externvardef.h" to avoid overriding?
This is a linker error, although there is #include protection around it in this header file. So this is not a compiler error, its a linker error, but why.
source share