Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should functions be made "extern" in header files?

Tags:

c

extern

Should functions be made extern in header files? Or are they extern by default?

For example, should I write this:

// birthdays.h struct person find_birthday(const char* name); 

or this:

// birthdays.h extern struct person find_birthday(const char* name); 
like image 640
bodacydo Avatar asked Jul 29 '10 21:07

bodacydo


People also ask

Should functions be in header files?

No. If you import the same header from two files, you get redefinition of function. However, it's usual if the function is inline. Every file needs it's definition to generate code, so people usually put the definition in header.

Can functions be extern?

The extern keyword in C and C++ extends the visibility of variables and functions across multiple source files. In the case of functions, the extern keyword is used implicitly. But with variables, you have to use the keyword explicitly.

Should externs be in header files?

All variables and functions in header files should be extern. Separate header files should be used for variables and functions. Use a C code file to declare the variables and functions and use this in end user code. Extern must be used instead of using global variables.

Can we declare extern in header file?

The file that contains the function declaration/implementation does not include the header file with the extern keyword. The file that calls the function does include the header file with the extern keyword, and that's a good thing.


1 Answers

From The C Book:

If a declaration contains the extern storage class specifier, or is the declaration of a function with no storage class specifier (or both), then:

  • If there is already a visible declaration of that identifier with file scope, the resulting linkage is the same as that of the visible declaration;
  • otherwise the result is external linkage.

So if this is the only time it's declared in the translation unit, it will have external linkage.

like image 89
Matthew Flaschen Avatar answered Sep 23 '22 16:09

Matthew Flaschen