Search code examples
cstaticheaderinlineextern

C - Should Function Implementations in Header use extern/inline/static?


I am using function implementations in a header file for simple code sharing. Minimal example:

foo.h:

#ifndef FOO_H
#define FOO_H

// potentially want to include extern/static/inline keyword for this function
int max(int x, int y) {
    return x < y ? y : x;
}

#endif

bar.c:

#include <stdio.h>
#include "foo.h"

int main() {
    printf("Max of 1 and 2: %d", max(1, 2));
}

I was suggested to the inline keyword for the functions implemented in the .h file. However, that gives me a linker error. If I use extern inline it does compile, but since I just guessed to try this I am not confident that it isn't dangerous/bad in some way.

Is using extern inline appropriate here? If not, what combination of static, extern, and inline should I use?


Solution

  • If you're going to put the implementation of a function in a header file, it must have the static storage class specifier. This restricts the visibility of the function name to only the translation unit (i.e. .c file) where it is ultimately built-in. Note that doing so means that if multiple source files include this header then each one will have its own copy of the function.

    Using inline as well as static is not necessary, but it can serve as a hint to the compiler to perform certain optimizations on it.