Where to declare global variables?
-
I have a C++ project with multiple .h and .cpp files and with a .cpp file containing the int main() function. Where do I declare global variables such that they can be accessed by the methods in the various .cpp files? I declared the variable before the main() function but there is an "undeclared variable" error. I tried creating a .h file to store the global variable and added the line: #include "globals.h" in the necessary .h files but there were all sorts of link errors.
-
I have a C++ project with multiple .h and .cpp files and with a .cpp file containing the int main() function. Where do I declare global variables such that they can be accessed by the methods in the various .cpp files? I declared the variable before the main() function but there is an "undeclared variable" error. I tried creating a .h file to store the global variable and added the line: #include "globals.h" in the necessary .h files but there were all sorts of link errors.
-
I have a C++ project with multiple .h and .cpp files and with a .cpp file containing the int main() function. Where do I declare global variables such that they can be accessed by the methods in the various .cpp files? I declared the variable before the main() function but there is an "undeclared variable" error. I tried creating a .h file to store the global variable and added the line: #include "globals.h" in the necessary .h files but there were all sorts of link errors.
The terms declare and define need to be clarified. A [global] variable should be defined once but may be declared many times. The extern keyword garrantees that a variable is declared but not defined. You could define your global variables somewhere in a source (.cpp) file and then extern (declare) them in a header file (e.g globals.h). So you only need to include that header in any file to access the globals.
-- ===== Arman
-
I have a C++ project with multiple .h and .cpp files and with a .cpp file containing the int main() function. Where do I declare global variables such that they can be accessed by the methods in the various .cpp files? I declared the variable before the main() function but there is an "undeclared variable" error. I tried creating a .h file to store the global variable and added the line: #include "globals.h" in the necessary .h files but there were all sorts of link errors.
See the FAQ 6.2 How do I share a global variable among my .CPP files?[^]
--Mike-- Visual C++ MVP :cool: LINKS~! Ericahist | PimpFish | CP SearchBar v3.0 | C++ Forum FAQ Dunder-Mifflin, this is Pam.