Does extern “C” have any effect in C?

扶醉桌前 提交于 2019-12-04 16:50:34

问题


I just got some C code that uses extern "C" to declare external functions like this:

extern "C" void func();

Is this valid C? I'm getting an error at this line, but I'm not sure if it's because of this or something else.


回答1:


No, it's not valid C. It should only be used in C++ code to refer to functions defined in C code. The extern "C" should be surrounded in a ifdef __cplusplus/#endif block:

// For one function
#ifdef __cplusplus
extern "C"
#endif
void func();

// For more than one function
#ifdef __cplusplus
extern "C"
{
#endif

void func1();
void func2();

#ifdef __cplusplus
}
#endif



回答2:


this is a C++ notation to tell the compiler/linker to use C calling standards.

Usually that line is wrapped in an pre-processor statement.

#ifdef __cplusplus
extern "C" {
#endif

// stuff

#ifdef __cplusplus
}
#endif



回答3:


Not valid in C. If present after preprocessing this will result in a diagnostic as per the standard.

For C++, this turns of name-mangling. See this for more details as to why it may be required. Can you post some more details?



来源:https://stackoverflow.com/questions/717729/does-extern-c-have-any-effect-in-c

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