简体   繁体   English

extern“C”对C有影响吗?

[英]Does extern “C” have any effect in C?

I just got some C code that uses extern "C" to declare external functions like this: 我刚刚得到一些使用extern“C”的C代码来声明这样的外部函数:

extern "C" void func();

Is this valid C? 这是有效的C吗? I'm getting an error at this line, but I'm not sure if it's because of this or something else. 我在这一行收到错误,但我不确定是不是因为这个或其他原因。

No, it's not valid C. It should only be used in C++ code to refer to functions defined in C code. 不,它无效C.它只应在C ++代码中用于引用C代码中定义的函数。 The extern "C" should be surrounded in a ifdef __cplusplus / #endif block: extern "C"应该包含在ifdef __cplusplus / #endif块中:

// 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

this is a C++ notation to tell the compiler/linker to use C calling standards. 这是一种C ++表示法,用于告诉编译器/链接器使用C调用标准。

Usually that line is wrapped in an pre-processor statement. 通常该行包含在预处理器语句中。

#ifdef __cplusplus
extern "C" {
#endif

// stuff

#ifdef __cplusplus
}
#endif

Not valid in C. If present after preprocessing this will result in a diagnostic as per the standard. 在C中无效。如果在预处理后出现,将导致按照标准进行诊断。

For C++, this turns of name-mangling. 对于C ++来说,这就是名称错误。 See this for more details as to why it may be required. 对于更多的细节,为什么可能需要它。 Can you post some more details? 你能发布更多细节吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM