I want do define a variable in the header and be able to use it in multiple files.
e.g. have variable a
defined somewhere and be able to use/change it in both
First off, don't do this. Global mutable state is usually a bad thing.
The problem is that once the linker finishes combining the files in your include statments, it has seen this twice, once in main.cpp and once in vars_main.cpp:
int a = 1;
float b = 2.2;
If you only put this in the header file, it shows up in multiple translation units, once for each cpp
file that includes your header. It's impossible for the compiler to know which a and b you're talking about.
The way to fix this is to declare them extern
in the header:
extern int a;
extern float b;
This tells the compiler that a and b are defined somewhere, not necessarily in this part of the code.
Then, in one of your cpp files you would define them:
int a = 1;
float b = 2.2;
That way, there's one well-defined place for the storage for a
and b
to live, and the compiler can connect the dots properly.