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

原因是: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语句外面

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值