Name mangling in C++ is the process by which the compiler generates unique names for functions, variables, and other symbols to support features such as function overloading, namespaces, and templates.
For example, if we have the following source code.
Let’s compile the C source file to an object file.
1
clang -c function.c -o function.o
Then, compile the C++ source file to an object file.
1
clang++ -c main.cpp -o main.o
Link object files to generate an executable. We will get an error.
1
clang++ function.o main.o -o main
1 2 3 4 5
Undefined symbols for architecture arm64: "foo(int)", referenced from: _main in main.o (found _foo in function.o, declaration possibly missing extern "C") ld: symbol(s) not found for architecture arm64
The reason is because, when we include function.h in main.cpp, the C++ compiler will mangle the function name. When we compile function.c, the C compiler will not perform name mangling. So, in main.cpp, it can not find the matching symbol name.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
> nm main.o
U __Z3fooi 0000000000000000 T _main 0000000000000000 t ltmp0 0000000000000030 s ltmp1
> nm function.o
0000000000000000 T _foo U _printf 0000000000000038 s l_.str 0000000000000000 t ltmp0 0000000000000038 s ltmp1 0000000000000048 s ltmp2
3.3 Using extern “C”
To solve this issue, we can introduce extern “C” when declaring functions to ensure that the function names remain consistent across both C and C++ code, enabling proper linkage.