| < Day Day Up > |
|
If you must use global variables and are programming multifile projects you will need to know how to control your variables across many files. In some cases you will want to make your global variables visible to all the files in your program; in others, you will want to limit the visibility of file scope variables to one file. Here’s how you do it...
File scope variables by default have external linkage meaning they are visible across all the files in your project. Examine the two source files shown in example 5.6:
Example 5.6: file scope linkage
#include <iostream> using namespace std; int a = 1; void someFunction(); void someFunction(){ cout<<a<<endl; } | #include <iostream> using namespace std; void someFunction(); extern int a; int main(){ a = 3; someFunction(); cout<<a<<endl; return 0; } |
File1.cpp | File2.cpp |
file1.cpp and file2.cpp represent two files belonging to the same project. file1.cpp contains the declaration and definition of someFunction() along with a global variable a which is assigned the value of 1. file2.cpp declares someFunction() again before calling it in the main() function. file2.cpp also declares the variable a but prefaces it with the keyword extern to tell the linker that the variable a has been declared and defined in another file and that you intend to use that variable in this file too.
When a is assigned the value 3 in the body of the main function, that’s the value printed to the screen when someFunction() is called.
If the keyword extern were to be left off the declaration of a in file2.cpp the following link error would occur when you tried to compile and run the program:
Link Error : multiply-defined 'a' (data) Defined in file1.cpp Defined in file2.cpp
Example 5.7 shows the same two files after being modified slightly:
Example 5.7: static linkage
#include <iostream> using namespace std; static int a = 1; void someFunction(); void someFunction(){ cout<<a<<endl; } | #include <iostream> using namespace std; void someFunction(); int a; int main(){ a = 3; someFunction(); cout<<a<<endl; return 0; } |
file1.cpp | file2.cpp |
The keyword static now prefaces the declaration of a in file1.cpp, limiting its visibility to file1.cpp. With file1.cpp’s variable a safely limited to file scope file2.cpp can declare its own variable a and use it as it sees fit. The results of calling someFunction() and executing the cout statement now produce different results, namely, the values 1 and 3 are printed to the screen.
| < Day Day Up > |
|