Using the extern keyword

When I declare function prototypes in my header files, I can cover them everywhere in my program, although I never use the 'extern' keyword. Are they only important for static libraries or when I need it?

+3


source to share


4 answers


Default functions extern

. The keyword extern

is only useful for variables.



+5


source


extern is the default storage class specifier in C.

Explicitly point it to variables

extern int i;

      

if it can be shared between modules. Then



int i;

      

in another module will not violate the ODR.

For functions, yes, pretty useless.

+2


source


They are optional for function declarations. They are only needed to declare external global variables:

// header
extern int foo;

// implementation (.c)
int foo;

      

Wihout extern

, the compiler will create a global variable every time it encounters it (because the header is included) and you get a linker error.

Another use case for this keyword is to make C ++ code compliant by specifying it with the C binding (this again prevents linker errors, namely those caused by C ++ name change):

#ifdef __cplusplus
extern "C" {
#endif

void foo(void);

#ifdef __cplusplus
}
#endif

      

+1


source


By default, all extern ..

The Extern keyword is only used for variables.

0


source







All Articles