The terminology used in textbooks, especially really old ones, doesn't always match the terminology used in the official standard or other texts.
From searching your quote, it appears it's from one of the following books:
• C++ A Beginner's Guide 2nd Edition (2003)
• C++ From The Ground Up, 3rd Edition (2003)
Their use of the word "module" should actually be "compilation unit", if I'm understanding correctly. (Not to be confused with C++20 modules.)
Is it like the cpp file, or the header file? |
A compilation unit is like a .cpp file. It's not exactly that, but it's close enough that I will handwave it.
If you have 2x .cpp files, they can be compiled separately (into object files) and then linked together during the build process.
So using the extern on an int would make that int var known to that header? |
Essentially, you have some global variable, and it needs to be stored somewhere because it is data. If you stored it in both .cpp files, you would get a multiple definition error because you're defining it more than once. So you need to declare one compilation unit as actually storing the variable, and the other compilation unit just references it by seeing it as an "extern" variable only.
Yes, marking it an extern in a header and then only defining the variable in one .cpp file (compilation unit) allows multiple compilation units to all refer to the same global variable.
_____________________
Example:
Let's say you have two cpp files, foo.cpp and bar.cpp.
foo.cpp
1 2 3 4 5 6
|
int a;
void foo()
{
a = 43;
}
|
bar.cpp
1 2 3 4 5 6
|
int a;
int main()
{
a = 42;
}
|
If you tried to compile + link both of these files, you would get a linker error.
g++ -Wall foo.cpp bar.cpp |
...\Temp\ccbaj2kT.o:bar.cpp:(.bss+0x0): multiple definition of `a'
...\Temp\ccUK2AGv.o:foo.cpp:(.bss+0x0): first defined here
collect2.exe: error: ld returned 1 exit status |
_____________________
With extern, you are telling the linker that you have a variable, but is defined in another compilation unit.
foo.cpp
1 2 3 4 5 6
|
int a; // DEFINED HERE
void foo()
{
a = 43;
}
|
bar.cpp
1 2 3 4 5 6
|
extern int a; // DECLARED AS EXTERN HERE
int main()
{
a = 42;
}
|
g++ -Wall foo.cpp bar.cpp |
Will compile + link. (This is just a minimal example.)