Maestro
Maestro

Reputation: 9508

Usage of the extern keyword

When I declare function prototypes in my header-files, I can reach those everywhere in my program, even though I never use the 'extern' keyword. Are they only important for static libraries, or when do I need it?

Upvotes: 3

Views: 232

Answers (4)

Raghu Srikanth Reddy
Raghu Srikanth Reddy

Reputation: 2711

By default, all the functions are extern..

Extern keyword is used only for variables..

Upvotes: 0

user529758
user529758

Reputation:

For function declarations, they're not mandatory. They're only needed for declaring external global variables:

// header
extern int foo;

// implementation (.c)
int foo;

Wihout the extern, the compiler would instantiate the global variable each time it encounters it (because the included header) and you'll get a linker error.

Another use case of this keyword is making C code C++-compatible by specifying it to be of C linkage (this again prevents linker errors, namely those caused by C++ name mangling):

#ifdef __cplusplus
extern "C" {
#endif

void foo(void);

#ifdef __cplusplus
}
#endif

Upvotes: 1

Konstantin Vladimirov
Konstantin Vladimirov

Reputation: 6999

extern is default storage class specifier in C.

Explicitly specify it on variables

extern int i;

if it can be shared between modules. Then

int i;

in other module will not violate ODR.

For functions yes, pretty useless.

Upvotes: 2

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272497

Functions are extern by default. The extern keyword is only useful for variables.

Upvotes: 5

Related Questions