Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ header files and variable scope

Tags:

c++

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?

like image 434
MrDatabase Avatar asked Feb 19 '26 23:02

MrDatabase


1 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.

like image 111
i_am_jorf Avatar answered Feb 21 '26 11:02

i_am_jorf



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!