Could someone please explain the C/C++ keyword ' extern ' , and it use , if possible please post some example.
Printable View
Could someone please explain the C/C++ keyword ' extern ' , and it use , if possible please post some example.
Search the Web for C keyword extern.
the short/incomplete version:
extern means you are telling the compiler to assume that some object of a certain type exists but that it shouldn't actually create this variable.
Some other .cpp file will declare (and create) the variable, or the variable will be part of an external linkage (.obj or .lib) you are linking with.
- The first case works, but is messy. It's better to define the variable in a .h and declare it (once) in one of the .cpp files.
- the 2nd case (external linkage) is the only 'clean' reason why you would have to use it.
thank you
Hi Paul,
Could you explain the difference between using "extern" on a function verses a global function?
Say I create two files named Globals.h and Globals.cpp.
- I code a function in Globals.cpp.
- I place the function declaration in Globals.h.
- I insert "#include "Globals.h" at the start of every file that needs to use that function.
This would be a global function would it not?
Now I prefix the function declaration with "extern" in the Globals.h file.
What's the difference with or without the "extern" prefix?
Thanks,
Raptor
Function names have external linkage by default, so there is no difference.
except when you meant
extern "C"
In that case, the extra "C" means you will get external linkage using the C convention instead of the normal C++ convention (with mangling).