Search code examples
clinker-errorsinline-functions

C inline functions


As far as i know, inline functions in C work pretty the same way as in C++ when used in single translation unit and there's no need to dive into extern inline difficulties in such a case. However, the following program including three files seems not to compile in C and I am struggling to figure out why.

f.h

int f();
inline int g();

f.c

#include "f.h"

inline int g() {
    return 5;
}

int f() {
    return 3 + g();
}

main.c

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

int main() {
    printf("%d", f());
    return 0;
}

The linker

tells that there is an undefined reference to g. However, as g is used only in f.c file, I can not define where the problem lies exactly.


Solution

  • From the C Standard (6.7.4 Function specifiers)

    7,,,For a function with external linkage, the following restrictions apply: If a function is declared with an inline function specifier, then it shall also be defined in the same translation unit

    In your project the function g is declared in the translation unit with main.