Hi, everyone,
what is the difference between global variable and file variable in C++?
Thanks!
Hi, everyone,
what is the difference between global variable and file variable in C++?
Thanks!
The only difference is that file variables are only accessible inside the file. But they have the same life time.
In C and C++ you can make a global variable only accessible from the file in which it's declared by using the static keyword in front of the declaration. Globals that don't use the static keyword are accessible from any C or C++ file compiled into the program.
The static global method is deprecated in C++ in favor of anonymous namespaces. Any declarations placed inside an anonymous namespace are also only accessible from within that file.
C++ programs are compiled one translation unit at a time (basically this means that each .cpp file is compiled independently).
By default, variables that are not const
, functions that are not inline
and typedef
s have internal linkage: this means that they are not visible to other translation units. If other translation units refer to a symbol having internal linkage (after declaring it, which requires the keyword extern
for variables), the linker won't be able to find them.
To explicitly require internal linkage use the keyword static
or, better, use unnamed namespaces.
Note: These rules apply to C++ just as well as C, with some dealings with class/struct/namespace scoping. (I did not notice the question was about C++, not C.)
Remember that (in most cases) C source files are compiled into object files. Object files have an 'export' table which tells the linker (when linking) what symbols it provides. A symbol is a name (its exact name depends on the ABI) referring to a function or variable (in most cases).
When you declare a global variable in your C source file, like this:
// fileA.c
int hello = 42;
void printMessage() {
printf("Hello, %d world(s)!\n", hello);
}
hello
and printMessage
are exported. When a C object file requests a symbol called 'hello
' (assuming a simple ABI), the linker connects that with the hello
exported by fileA.c
.
Now for the other case. When you declare a file-local variable like this:
// fileB.c
static int world = 9001;
static void messagePrint() {
printf("It's over %d!\n", world);
}
world
and messagePrint
are not exported. When a C object file requests a symbol called 'hello
', the linker cannot connect that with the hello
of fileB.c
because there is no information about it in fileB.obj
(or whatever).
How can messagePrint
know about world
, though? Both are in the same translation unit. Scope takes over here. I'm sure you'll find lots of information on scope through Google.
(Is having the symbol name match the function/variable name standard in C? I know it differs for C++ (where there is no standardization for name mangling), which is why I mention ABI in the first place.)
((If ABI the correct term, even? ;P))