Search code examples
cclanginline

Why do I get a linking error with clang when inlining a function in a C program?


Why doesn't the following program compile with clang?

#include <stdio.h>

inline int f() {
  return 42;
}

int main() {
  printf("%d\n", f());
}

I get the following:

$ clang -o inline inline.c
Undefined symbols for architecture arm64:
  "_f", referenced from:
      _main in inline-975155.o
ld: symbol(s) not found for architecture arm64
clang-12: error: linker command failed with exit code 1 (use -v to see invocation)

But I can compile it with clang++ just fine. Is there some nuance between inline in C vs C++?


Solution

  • Very simple: Inlining does not work if you do not enable optimizations.

    enter image description here

    https://godbolt.org/z/KrWq4PGhd

    To sort this problem out you need to instruct the compiler to emit not inline version as well:

    extern inline int f() {
      return 42;
    }
    

    Then it will work in both cases (will be inlined or not)

    enter image description here https://godbolt.org/z/dh3G18PqK

    CLANG works exactly the same way:

    https://godbolt.org/z/ssMnzf5MG

    https://godbolt.org/z/ssMnzf5MG