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?
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 typeintcalledxexists 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 ofxto the one definition that it finds in one of the compiled source files. For it to work, the definition of thexvariable 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 thestatickeyword.header:
source 1:
source 2: