I'm trying to get my .cpp files to interact with eachother using .h files. But everytime I try to compile it it says the variables are already defined in the header file.
I get these errors:
1 2 3 4 5 6
c:\users\gebruiker\desktop\grid control\grid control\grid control\loadimages.cpp(37): error C2086: 'SDL_Surface *horStripeImage' : redefinition
1> c:\users\gebruiker\desktop\grid control\grid control\grid control\loadimages.h(6) : see declaration of 'horStripeImage'
1>c:\users\gebruiker\desktop\grid control\grid control\grid control\loadimages.cpp(38): error C2086: 'SDL_Surface *verStripeImage' : redefinition
1> c:\users\gebruiker\desktop\grid control\grid control\grid control\loadimages.h(7) : see declaration of 'verStripeImage'
1>c:\users\gebruiker\desktop\grid control\grid control\grid control\loadimages.cpp(39): error C2086: 'SDL_Surface *playfieldImage' : redefinition
1> c:\users\gebruiker\desktop\grid control\grid control\grid control\loadimages.h(8) : see declaration of 'playfieldImage'
You can declare a variable/function many times, but there has to be only one definition. You have re-defined the variables in loadImages.cpp. Although i would use extern just as Catfish proposed, it's considered redundant in C++.
Although i would use extern just as Catfish proposed, it's considered redundant in C++.
How so? If you want to access a global variable defined in a source file, you will need to declare it as extern somewhere - best bet is the header file of that source file.
@cire, this is linked to the OP's example (again), but the following
1 2 3
externint x = 3;
int x = 3;
are essentially equivalent, so had Staygold defined the images the first way, he could have just dropped the extern. Do note that it is not my personal opinion, but rather what i've read in "The C++ Programming Language" not too long ago. Apart from the
cases in which you have to use extern as Catfish mentioned, it also conveys your intents better and makes them explicit.
@cire, this is linked to the OP's example (again), but the following
1 2
externint x = 3;
int x = 3;
re essentially equivalent, so had Staygold defined the images the first way, he could have just dropped the extern.
You responded to and referenced Catfish's post, where extern was required and far from redundant. If the OP had moved the initialization and definition of the variables to the header file as you seem to be suggesting, he would've had redefinitions of the variables in multiple source files. I don't see your point.
2 A declaration is a definition unless ... it contains the extern specifier (7.1.1) or a linkage-specification25 (7.5) and neither an initializer nor a function body,