C/C++ global vs static global [duplicate]
Solution 1:
Global variables (not static
) are there when you create the .o
file available to the linker for use in other files. Therefore, if you have two files like this, you get name collision on a
:
a.c:
#include <stdio.h>
int a;
int compute(void);
int main()
{
a = 1;
printf("%d %d\n", a, compute());
return 0;
}
b.c:
int a;
int compute(void)
{
a = 0;
return a;
}
because the linker doesn't know which of the global a
s to use.
However, when you define static globals, you are telling the compiler to keep the variable only for that file and don't let the linker know about it. So if you add static
(in the definition of a
) to the two sample codes I wrote, you won't get name collisions simply because the linker doesn't even know there is an a
in either of the files:
a.c:
#include <stdio.h>
static int a;
int compute(void);
int main()
{
a = 1;
printf("%d %d\n", a, compute());
return 0;
}
b.c:
static int a;
int compute(void)
{
a = 0;
return a;
}
This means that each file works with its own a
without knowing about the other ones.
As a side note, it's ok to have one of them static
and the other not as long as they are in different files. If two declarations are in the same file (read translation unit), one static
and one extern
, see this answer.
Solution 2:
A name that's static in each file should not cause name collisions. If you're seeing that, please post (short) demo code showing it, along with the exact compiler you're using so we can properly verify the code and assuming it's correct, proper vilify the compiler.
Just FWIW, the preferred method in C++ is to use an anonymous namespace instead:
namespace {
int not_a_static_variable;
}
In all honesty, no I can't point to a lot of objective advantage to that though...