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:
#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
#include "externvardef.h"
int superGlobal;
#include "externvardef.h"
#include <stdio.h>
void go();
#include "filethatUsesSuperglobal1.h"
void go()
{
printf("%d\n", superGlobal );
}
#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.
Think about if from the code perspective - there is this symbol superGlobal
that points at an integer.
You have a bunch of .o files to link together into a single executable. Each of the .o files has it's own superGlobal
symbol. Which should the linker use?
The extern
declaration says: another of the compilations units (.o files) is going to declare this symbol, so I can use it. Thus there is only one copy so the linker knows what to do.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With