I want to organize my c++ variables and functions in the following way: function prototypes in a header file "stuff.h", function implementation in "stuff.cpp", then say #include "stuff.h" in main.cpp (so I can call functions implemented in stuff.cpp). So far so good. Now I want to declare some variables in stuff.cpp that have global scope (so I can modify the variables in functions implemented in stuff.cpp and main.cpp). This doesn't seem to work. How can I do this?
- 2If you're not using classes, C++ may not be for you.i_am_jorf– i_am_jorf2010-05-21 23:57:37 +00:00Commented May 21, 2010 at 23:57
- 1you must always think from the viewpoint that somebody else will use your stuff.cpp so having global variables can collide with existing definitions is one of the reasons not to use globals.AndersK– AndersK2010-05-22 00:08:54 +00:00Commented May 22, 2010 at 0:08
- 1The three above comments are not useful. They are personal opinions. They posters do not know the context in which the OP is working. What he wants may be appropriate for his situation. If these were answers I would flag them as inappropriate.Rudy– Rudy2019-06-19 11:51:43 +00:00Commented Jun 19, 2019 at 11:51
2 Answers
Declare them as extern. E.g., in stuff.h:
extern int g_number; Then in stuff.cc:
int g_number = 123; Then in main.cc just #include stuff.h.
2 Comments
If you write a variable "Declaration" [*1] in a header file that you include in the main src file and all source files that the variable appears in [*2]...
...And you write a:
#ifndef STUFF_H #define STUFF_H ... #endif around the content in the "stuff.h" header file...
...You can give all the variables and prototypes that you have "Declared" [*1] in that header file global scope.
What I usually do, is create header files for all my src files, to store: macros, prototypes, type-definitions and global-declarations; specific to the content in its associated src file.
Then, I create a "global_header.h" file to store all external and internal header inclusions [*3], all macros without a specific header-file home, all global variables without a specific header-file home, and so on; practically everything that you would want global, and at the top of your compiled super-file.
Then, (like all header files) I rap the global_header.h in a "#ifndef" security measure,
Then I have a single header that I can include at the top of all header files that gives access for all files to all header files,
I then tend to put this global header file at the top of all header files, and then just "#include" the specific header files at the top it's accosiated src file.
[*1]: (reserve a variable name and dataspace for it, without actually assigning a value to it.)
[*2]: (whether if that's a header specifically for global variables, or a header file specifically for the src file that you define the variable in (Eg: a "stuff.h" header file for the "stuff.{c/cpp/whatever}" src file).)
[*3]: (#include "stuff.h" / #include <std.stuff.h>)