views:

53

answers:

1

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?

+8  A: 

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.

jeffamaphone
The header bit is actually not entirely necessary. You can declare extern nearer to call site in cpp files that need access to it. Generally though this is the way to do it.
Noah Roberts
It is necessary if you're committed to clean code. To repeat the declaration in every .cpp is prone to inconsistencies. When you declare it as an extern in the header, you assure that everyone uses it as the same type. And also the compiler will balk if the extern declaration in the .h and the definition in stuff.cc don't match.
Fabio Ceconello