Home > Net >  Why can't a static variable defined in one cpp file be found in another in c ?
Why can't a static variable defined in one cpp file be found in another in c ?

Time:10-28

I have a variables.cpp, in which it defines:

static MyNamespace::MyClass myObj('input');

I have a variables.h that is included by variables.cpp

And I have a main.cpp that includes variables.h, which it refers to myObj:

MyNameSpace::myObj.doRun();

And the compiler complains that: no member named 'myObj' in namespace 'MyNameSpace'

What am I doing wrong?

CodePudding user response:

The very purpose of static variables is to be file scope, not visible in other files. So naturally they are not then visible, using static specifically requests that.

As a consequence, several .cpp files can have a static variable with same name, and they will be different variables. Also as a consequence, if you define a static variable in .h file, then every .cpp file which includes it will have a different variable.

Extra notes:

  • In C you can achieve similar effect (file scope) by putting the variables in anonymous namespace in the .cpp file.

  • static class member variables are a different case, they are visible everywhere (in other words, the variable symbol name is exported), and basically behave like non-static global variables which aren't member variables. Yes, it can be a bit confusing, static has several different meanings in C .

  • static variable can be accessed from other .cpp files, if you create a function which returns a reference (or a pointer) to it in the .cpp file where it is defined. It's lifetime is same as program execution, so this is safe from that point of view. However, thread safety and re-entrancy are then issues which need attention, so you shouldn't do this unless you know why you are doing this.

CodePudding user response:

as another answer point out, static variable is meant to not shared with others.


If you do want to share myObj, you should remove the static specifier

// variables.cpp
MyNamespace::MyClass myObj('input'); // no static

and declare it in header file

// variables.h
extern MyNamespace::MyClass myObj;

or, with c 17, another option is use inline variable.

// variables.h
inline MyNamespace::MyClass myObj('input');

// variables.cpp
// do not redeclare it 

btw, 'input' is multicharacter literal, most likely not what you want.

  •  Tags:  
  • c
  • Related