您的位置:首页 > 编程语言 > C语言/C++

C++调用C编译的变量和函数为什么需要extern

2013-01-22 22:13 363 查看
原因是:C++里不同的namespace和类,等等结构里可以存在名字相同但实现不同的变量或函数,这是怎么实现的呢?

这就要了解C++的Name Mangling,中文也可叫命名编码吧,也有叫名字粉碎机的 :)

摘抄一段

Name mangling is the encoding of function and variable names into unique names so that linkers can separate common names in the language. Type names may also be mangled. Name mangling is commonly used to facilitate the overloading feature and visibility
within different scopes. The compiler generates function names with an encoding of the types of the function arguments when the module is compiled. If a variable is in a namespace, the name of the namespace is mangled into the variable name so that the same
variable name can exist in more than one namespace. The C++ compiler also mangles C variable names to identify the namespace in which the C variable resides.

意思主要是讲:为了支持同名变量或函数,C++往往会把结构,scope等名字加到用户定义的变量名前面,作为前缀,这样就避免了重复。

但C语言没有Name Mangling,全局的变量和函数都是全局命名,用户定义的什么名字,实际上就是什么名字。

所以,为了避免C++的编译器拿到C编译的代码也采用Name Mangling的方式来解析,所以需要加上extern "C",告诉编译器应该如何处理。

extern "C" {
extern "C++" {
void func();
}
}

但如果extern出现了嵌套,最后的处理方式采用就近原则,即上述代码会用C++的方式来处理func。注意嵌套的extern语句不被MSVC支持,VS下会报错。

所以,#include语句必须放在extern语句外面
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐