Hello everybody. I have a question regarding global variables in a project with many source code files. I have already defined a class called "sprite" and I would like to declare an instance of sprite so that all functions and classes can access it no matter what .h or .cpp file they happen to be located in. (That is, make it global to ALL .cpp and .h files)
Presently, I've declared:
sprite ball;
outside of all functions and classes in one of my .cpp files. Now this works just fine for all functions defined in the same .cpp file but when I try to access ball in the main function (in a separate .cpp file), the compiler tells me that the identifier "ball" is undefined.
I've tried several things to make this work including declaring the sprite using "extern" in the main function's .cpp file as well as trying to make a new namespace for the ball but I get the same problem: it cannot be accessed outside the same .cpp file. Any advice would be really appreciated! Thanks!
I have tried this also however that causes a multiply-defined symbol error. I have also tried using #pragma once but again, this still leads to the same error. Thanks for the suggestion though.
Here we go. Define it in just one .cpp or somewhere that is only included once and in every file that needs the variable (except the ones that already have it, of course) repeat the declaration, but add extern before it.
Example: