Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ reference variable across files

Tags:

c++

variables

I have a project where I need to reference a variable declared in one CPP file in another, is that possible?

If so, how?

like image 268
Tony The Lion Avatar asked Jul 04 '26 07:07

Tony The Lion


1 Answers

It is possible, if you declare it as global (top-level, above any function definition) and use "extern ;" in other files to make it known to the compiler.

// Main.cpp
#include <...>

int myNum;

int main(int argc, char** argv)
{
   // MAGIC BE HERE
   return 0;
}

and

// Second.cpp
#include <...>

extern int myNum;

int f()
{
   return myNum * 2;
}

extern prevents the compiler from allocating memory again when a variable was allocated in another file.

like image 89
LukeN Avatar answered Jul 05 '26 21:07

LukeN



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!