extern keyword can be used as

  • a storage class specifier for a variable
  • to tell the compiler how to link to an external function.

extern

The extern keyword is used to inform the compiler about variables declared outside of the current scope. Variables described by extern statements will not have any space allocated for them, as they should be properly defined elsewhere.

Extern statements are frequently used to allow data to span the scope of multiple files. An external variable must be defined, exactly once, outside of any function.

extern int GlobalVar;
extern void Action (int* State );

extern “C” and mangling

Since C++ has overloading of function names and C does not, the C++ compiler cannot just use the function name as a unique id to link to, so it mangles the name by adding information about the arguments. A C compiler does not need to mangle the name since you can not overload function names in C. When you state that a function has extern “C” linkage in C++, the C++ compiler does not add argument/parameter type information to the name used for linkage. For example {test.cpp}

void foo() { } 
$ g++ -c test.cpp 
$ nm test.o | grep foo
0000000000000000 T _Z3foov

foo function is decorated. Now with {test.cpp}

extern "C" {
void foo() { } 
}
$ g++ -c test.cpp
$ nm test.o | grep foo
0000000000000000 T foo

foo function is not decorated.

If you want to mix C and C++ code add the following guards in your C code.

#ifdef __cplusplus 
extern "C" { 
#endif 
/* statements */
#ifdef __cplusplus 
} 
#endif

This allows to have the good decoration when you link with the C/C++ libraries.