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);
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With