Reputation: 54
I am making a C++ project with the main.cpp which has main function, then a header file header.h and a cpp file program.cpp which has class methods in it. So I wanted to ask is there a way to declare a variable that i would use in main.cpp and methods could read it in program.cpp ?
Upvotes: 0
Views: 69
Reputation: 27577
Global variables are discouraged in general, but you can do this simply with the following in your header file:
extern my_global_type myGlobal;
you then define myGlobal
in main.cpp
as:
my_global_type myGlobal = \* some init value *\;
and simply use it in program.cpp
by including the header with the above extern
. You can make it a bit less global (but not get rid of all the problems) by putting myGlobal
in a namespace
.
Upvotes: 2
Reputation: 385204
Yes.
Look up the extern
keyword in your C++ book.
Upvotes: 4