tags:

views:

144

answers:

5

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);

Thanks, Boda Cydo.

+3  A: 

They are implicit declared with "extern".

tur1ng
+5  A: 

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.

Matthew Flaschen
+3  A: 

No, functions do not need to be declared extern.

But variables #included from multiple files do http://www.velocityreviews.com/forums/t313929-extern-variables-and-header-files.html

nonnb
+1  A: 

Functions declared in headers are normally (unless you work really hard) extern. Personally, I prefer to see the explicit keyword there - but the compiler doesn't need it. It reminds the readers that they are extern, and since humans are more fallible than computers, I find the reminder helps.

With variables, it is important to use the extern keyword (and no initializer) in the header file. Consequently, for symmetry with the (very few) global variables declared in headers, I use extern with the function too - even though it is strictly not necessary.

Jonathan Leffler
I add the explicit `extern` a well; declarations in header files are either `extern` or `static inline` for functions and `extern` or `static const` for variables; anything else is rarely needed
Christoph
A: 

I never bother with the "extern" in my source code, but some people do. To my mind, having extern before variables but not functions makes it more visually obvious which things are functions and which things are variables (possibly including function pointers). I think a lot probably depends on how the declarations in the .h file are created, and how they relate to the main .c file. I usually start by typing in the .h file prototypes, and then copy/paste to the .c file and add the function body (striking the semicolon at the end of the prototype), so "extern" would require have to be added to the header file or struck from the main .c file after the copy/paste.

supercat