I'm reading "Think in C++" and it just introduced the extern
declaration. For example:
extern int x; extern float y;
I think I understand the meaning (declaration without definition), but I wonder when it proves useful.
Can someone provide an example?
the extern keyword is used to extend the visibility of variables/functions. Since functions are visible throughout the program by default, the use of extern is not needed in function declarations or definitions. Its use is implicit. When extern is used with a variable, it's only declared, not defined.
You do not necessarily "need" extern for variables. When C was invented Unix linkers were also written, and they advanced the art in unheralded but clever ways. One contribution was defining all symbols as small "common blocks".
The extern “C” keyword is used to make a function name in C++ have the C linkage. In this case the compiler does not mangle the function.
“extern” keyword is used to extend the visibility of variables/functions(). Since functions are visible through out the program by default. The use of extern is not needed in function declaration/definition. Its use is redundant.
This comes in useful when you have global variables. You declare the existence of global variables in a header, so that each source file that includes the header knows about it, but you only need to “define” it once in one of your source files.
To clarify, using extern int x;
tells the compiler that an object of type int
called x
exists somewhere. It's not the compilers job to know where it exists, it just needs to know the type and name so it knows how to use it. Once all of the source files have been compiled, the linker will resolve all of the references of x
to the one definition that it finds in one of the compiled source files. For it to work, the definition of the x
variable needs to have what's called “external linkage”, which basically means that it needs to be declared outside of a function (at what's usually called “the file scope”) and without the static
keyword.
#ifndef HEADER_H #define HEADER_H // any source file that includes this will be able to use "global_x" extern int global_x; void print_global_x(); #endif
#include "header.h" // since global_x still needs to be defined somewhere, // we define it (for example) in this source file int global_x; int main() { //set global_x here: global_x = 5; print_global_x(); }
#include <iostream> #include "header.h" void print_global_x() { //print global_x here: std::cout << global_x << std::endl; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With