I saw this code where lots of static variables are initialized in headers like

bla.h

Code:

static const long TM_X = 50;
static const long TM_Y = 50;

Anyone knows what happens when I include this file from ten cpp files?
A separate instance of every variable gets created every time the header is included?

03-17-2009

matsp

Yes, every file gets it's own copy of the variables. Since they are const, it won't matter much. Most likely, unless you take the address of either variable, the compiler should not use any memory for the variables.

--
Mats

03-17-2009

brewbuck

In C++, a const POD value will not be given an address in memory unless somebody attempts to take that address (pointer or reference). And even if it does create a variable, the linker should fold all the copies together at link time. This was one of the major improvements of "const" in C++.

But the fact that you are using "static" makes it even less of a problem, since the name will not be visible outside of any one module in the first place. I wouldn't have bothered with the "static" personally, but the idea of placing a const definition in a header is totally legitimate -- C++ is attempting to eradicate most usages of the preprocessor, and this is one of the cases where it was specifically meant for.