There are few global variables which are static in one of the header files. I see these variables are used in the associated .cc files. So, looks like this has no issues.
My questions are:
-
Whats the difference between including a global variable vs static global variable ?
I know static global doesnt have visibility outside its file. But dont know how this would work when it comes as part of a .h which is #included. -
I wrote a sample program, and tried the same thing. But, I get compilation error the moment I make the variable static. When it is just global, it is fine.
So, is there something which I am missing on a regular g++ build ? (Please note, the initial case was on our official code base which has enough makefiles, .h files and all).
Thanks for the help !
Here is my sample program :
.h file:
#include <iostream>
typedef unsigned int uint;
static const int appk=189;
class abc1
{
public:
abc1(int x);
virtual void printVal();
};
.cc file:
#include "abc1.h"
extern int appk;
abc1::abc1(int x)
{
}
void abc1::printVal()
{
printf("abc1 print: %d\n", appk);
}
(1) If you put a global variable in a
.hfile and include it in various .cpp/.cc files then it will be defined multiple times for every file. So you are most like to get a linker error.To overcome that, mostly you are likely to use
externkeyword:and define that in only one translation unit:
(2) If you put a
staticglobal in a.hfile and include it, then you will not get any error, because for every different translation unit, there will be a different copy for thatstaticglobal variable.However, such usage is deprecated; instead of that it’s better to use unnamed
namespace:From your question, I don’t see that you should get any linker error for
staticglobal.