Reputation: 44505
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?
Upvotes: 2
Views: 3406
Reputation: 1
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>
)
Upvotes: 0
Reputation: 54640
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
.
Upvotes: 9