I have three files, a main .cpp file:
#include <stdio.h>
#include "myClass.h"
int main()
{
myClass mvar;
tryVar = 23; // why does this not work?
printf("%d ", mvar.readTryVar()); // This writes out 0, why??
return 0;
}
a myClass.cpp file
#include "myClass.h"
myClass::myClass(void)
{
}
myClass::~myClass(void)
{
}
void myClass::setTryVar()
{
tryVar = 23334;
}
int myClass::readTryVar()
{
return tryVar;
}
and a myClass.h file
#pragma once
static int tryVar;
class myClass
{
public:
myClass(void);
~myClass(void);
void setTryVar();
int readTryVar();
};
They’re very simple files, however I can’t understand why the static variabile isn’t set in the main function and I need to set it through the myClass functions.
I think that I don’t know very well how the “translation units” are created, I know that the “include” directive simply copies the content of the header file into the .cpp file before the actual compilation.. then why isn’t the static variable visible?
statichas multiple meanings. Outside aclass, it declares a variable that is unique to every translation unit, somain.cppandmyClass.cpphave their own copies.To accomplish what you want, you need an
externvariable: