声明“extern”C“的效果是什么?在头文件到C ++共享库? [英] What is the Effect of Declaring 'extern "C"' in the Header to a C++ Shared Library?

查看:112
本文介绍了声明“extern”C“的效果是什么?在头文件到C ++共享库?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据这个问题,我了解结构的目的在链接C库与C ++代码。现在假设如下:

Based on this question I understand the purpose of the construct in linking C libraries with C++ code. Now suppose the following:

我有一个'.so'共享库用C ++编译器编译。头部有一个'typedef stuct'和一些函数声明。如果标头包含externC声明...

I have a '.so' shared library compiled with a C++ compiler. The header has a 'typedef stuct' and a number of function declarations. If the header includes the extern "C" declaration...

#ifdef __cplusplus
extern "C"
{
#endif

  // typedef struct ...;
  // function decls

#ifdef __cplusplus
}
#endif

...效果是什么?具体来说,我想知道是否有任何有害的声明的副作用,因为共享库被编译为C ++,而不是C。

... what is the effect? Specifically I'm wondering if there are any detrimental side effects of that declaration since the shared library is compiled as C++, not C.

有任何理由有extern C声明在这种情况下?

Is there any reason to have the extern "C" declaration in this case?

推荐答案

这是重要的,以便编译器不会命名mangle。

This is important so that the compiler doesn't name mangle. C++ uses name mangling to differentiate functions with operator overloads.

对二进制文件运行/ usr / bin / nm,看看C ++对你的函数名是什么:
_ZSt8_DestroyIN9__gnu_cxx17__normal_iteratorIPiSt6vectorIiSaIiEEEEiEvT_S7_SaIT0_E

Run "/usr/bin/nm" against a binary to see what C++ does with your function names: _ZSt8_DestroyIN9__gnu_cxx17__normal_iteratorIPiSt6vectorIiSaIiEEEEiEvT_S7_SaIT0_E

externC可防止该名称的变形。

extern "C" prevents that name mangling.

IIRC,以在运行时动态链接符号。这是插件类型架构的常见问题。

IIRC, that makes it possible for program to dynamically link in symbols at run time. It's common for "plugin" type architectures.

这篇关于声明“extern”C“的效果是什么?在头文件到C ++共享库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆