This question isn't so much a 'how to solve' question as its a question about why doesn't this work?
In C++ I can define a bunch of variables that I want to use across multiple files in a few ways.
I can do it like this:
int superGlobal;
#include "filethatUsesSuperglobal1.h"
int main()
{
// go.
}
That way ONLY works if "filethatUsesSuperglobal1.h" has its entire implementation there in the header and no attached .cpp file.
Another way (the "morer correcter" way) is to use extern:
externvardef.h
#ifndef externvardef_h
#define externvardef_h
// Defines globals used across multiple files.
// The only way this works is if these are declared
// as "extern" variables
extern int superGlobal;
#endif
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 nit picky question, but Why do I need to declare it extern - should not the #include guards on "externvardef.h" avoid redefinition?
Its a linker error, even though that header file has #include guards around it. So its not a compiler error, its a linker error, but why.