Difference extern“C” vs extern

随声附和 提交于 2019-12-04 05:20:21
Dmitry Poroh

extern "C" means to call C-library function from C++ code.

What is the difference?

A long, long time ago C-compilers generated code and addressed functions by name only. It didn't consider parameters.

When overloaded functions were introduced in C++, extern "C" was required to specify the same name for different functions. For example void f() and void f(int) are two different functions in C++.

The C++ compiler accomplished this via name-mangling. It adds some info to the function name related to the functions parameters.

extern "C" is a command to the compiler to "refer to the older style naming convention - without mangling".

There is a difference between those two things.

The first says "the functions in here should be compiled so as to be callable from C". C++ allows multiple functions to have the same name as long as they take different arguments. C does not. To achieve that, C++ includes argument type information in the compiled name of its functions. As a result a C compiler will not be able to find the functions. If you add an extern "C" then you instead get C behaviour, but you gain the ability to call those functions from C.

The latter says "this function exists in another compilation unit". Which means that a compiler should trust that the function with that signature exists but not worry about being unable to see it. It'll be there when you link, you promise. Declarations (contrasting with definitions) are extern by default since at least C99.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!