Home extern "C" - what does it exactly do?
Post
Cancel

extern "C" - what does it exactly do?

About 9 years ago I was trying to make games with C++. I used Lua for scripts. It was shipped as a package containing a static library (lua.lib for Windows) and header files. Since Lua is written in C and lua.lib was compiled with a C compiler, I needed to include the headers this way:

1
2
3
4
5
extern "C" {
#include <lua.h>
#include <lualib.h>
#include <lauxlib.h>
}

At that time I didn’t have a clue what it would mean at all. Of course, after some time I learned that it’s about functions overloading. The compiler needs to distinguish overloaded functions between each other.

There is no function overloading in C, so the object file gets the “pure” name of the function. While using the C++ compiler, the object file gets the “mangled” name of the function. There is name mangling in C++.

1
2
void hello(int, char) -> hello (in C)
void hello(int, char) -> _Z1helloic (in C++)

The extern "C" expression is needed to declare that all functions and variables declared in its scope should have the “pure” name in the object file. In essense, it’s needed to make inter-operability between C++ and C code possible. Link to godbolt. It’s a hint to the linker that you want to call a C function from a C++ code.

But what’s about the code inside the extern "C"? Is it being compiled as C++ code or as C code? The belief that “C is a subset of C++” is wrong: the two languages are evolving independently. C has features that C++ doesn’t have, for example VLA.

The C++ Standard shows examples where the code inside extern "C" is compiled as C++ code: [dcl.link] (there are classes).

Inspecting the source code of a compiler, it becomes clear that we compile C++ code inside extern "C", and the only thing that changes is the flag about mangling the name: Clang’s source code.

The conclusion: header files of a C library should be simple enough, so that both C and C++ compilers could compile them in the same way.

This post is licensed under CC BY 4.0 by the author.

Fast Pimpl

📚 Book review: "Advanced C and C++ compiling" (2014)