Difference extern“C” vs extern

柔情痞子 提交于 2019-12-06 01:20:19

问题


Is there a difference whether I use the extern "C" specifier for the entire header, or specify extern for every function?

As far as I know, there is none, since only functions and variables can be linked externally, so when I use the extern specifier before every function prototype and extern variable, I have no need to use the global extern "C" declaration!?

Example A:

#ifdef __cplusplus
extern "C" {
#endif

void whatever(void);

#endif

Example B:

extern void whatever(void);

回答1:


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".




回答2:


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.



来源:https://stackoverflow.com/questions/44056461/difference-externc-vs-extern

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