I am for the first time working on a larger C++ project. Now I need to share variables between two .cpp files. Namely I have variables that get edited in main.cpp and need to see their state in animals.cpp. What is the best way to share them between them? The way I was trying to do it was have another header file (variables.h) in which I had a class with static members that would then act as these variables. Sample code to explain:
variables.h:
class a {
public:
static int x;
static void init();
};
variables.cpp:
#include "variables.h"
void a::init() {
x = 1;
}
animals.h:
void print_x();
animals.cpp:
#include "variables.h"
#include <iostream>
void print_x(){
std::cout << a::x;
}
main.cpp:
#include "variables.h"
#include "animals.h"
int main(){
a::init();
a::x = 2;
print_x();
}
When I compile together all .cpp files this however gives me the error:
objects.a(variables.cpp.obj):variables.cpp:(.rdata$.refptr._ZN1a1xE[.refptr._ZN1a1xE]+0x0): undefined reference to `a::x'
I do not necessarily want to achieve this sharing of variables with a class in a third header+cpp file but rather ask for the best way to do this.
I have looked at answers to similar problems where external
was suggested. However I do not really want to create global variables and as I have understood it, external
is used to share global variables.
Thanks for your help!