Exercise 3-10 (static variable and function, file scope)
Chapter_3 Exercise_3-9 | Forward Exercise_3-11 |
Exercise 3-10 TCP1, p. 228
Exercise 3-10. Try to compile and link FileStatic1.cpp with FileStatic2.cpp. What does the resulting error message mean?
CONTENTS: FileStatic1.cpp FileStatic2.cpp
FileStatic1.cpp TCP1, p. 163 download
// File scope demonstration. Compiling and linking this file with
// FileStatic2.cpp will cause a linker error
// File scope means only available in this file:
static int fs; // global static variable (or function) has file scope
extern void func(); // Trying to reference func()
int main()
{
fs = 1;
func();
return 0;
}
/*
g++ -c FileStatic1.cpp FileStatic2.cpp // create object files
g++ -c FileStatic*.cpp
g++ FileStatic*.o -o FileStatic // link object files, create executable
/usr/bin/ld: FileStatic1.o: in function `main':
FileStatic1.cpp:(.text+0x13): undefined reference to `func()'
/usr/bin/ld: FileStatic2.o: in function `func()':
FileStatic2.cpp:(.text+0xa): undefined reference to `fs'
collect2: error: ld returned 1 exit status
*/
Note: In FileStatic1.cpp, the static global variable fs has file scope, so it is unavailable in FileStatic2.cpp. Similarly, the static function func() defined in FileStatic2.cpp has file scope, so it is unavailable in FileStatic1.cpp, generating the linking errors above. Because of the linking errors, no executable is produced.
FileStatic2.cpp TCP1, p. 163 download
extern int fs; // Trying to reference fs
static void func() // file scope
{
fs = 100;
}
/*
g++ -c FileStatic2.cpp // create object file
*/
Chapter_3 Exercise_3-9 | BACK_TO_TOP | Forward Exercise_3-11 |
Comments
Post a Comment