gpt4 book ai didi

c++ - 什么时候使用 extern "C"?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:53:37 24 4
gpt4 key购买 nike

我知道如何使用 extern "C" 但必须在什么条件下使用它?

extern "C" tells the C++ compiler not to perform any name-mangling on the code within the braces. This allows you to call C functions from within C++.

例如:

#include <string.h>

int main()
{
char s[] = "Hello";
char d[6];

strcpy_s(d, s);
}

虽然这在 VC++ 上编译得很好。但有时这会写成:

extern "C" {   
#include <string.h>
}

我不明白这一点。你能举一个需要 extern "C" 的真实例子吗?

最佳答案

您使用extern "C" 来防止头文件和您的 C++ 对象文件中的名称混淆,对于已经编译但没有混淆的库或对象。

例如,假设您有一个 widget 库,它是用 C 编译器编译的,所以它发布的接口(interface)是未损坏的。

如果您将头文件原封不动地包含在您的代码中,它会假定名称​​被损坏,而这些损坏的版本就是您告诉链接器要查找的内容。

但是,由于您将要求类似 function@intarray_float_charptr 的东西,而 widget 库将只发布了 function,所以您我们会遇到问题。

但是,如果您将它包含在:

extern "C" {
#include "widget.h"
}

您的编译器会知道它应该尝试使用 function,即未损坏的版本。

这就是为什么要包含在 C _or C++ 程序中的 C 内容的头文件中,您会看到如下内容:

#ifdef __cplusplus
extern "C" {
#endif

// Everything here works for both C and C++ compilers.

#ifdef __cplusplus
}
#endif

如果您使用 C 编译器来包含它,#ifdef 行将导致 extern "C" 内容消失。对于 C++ 编译器(定义了 __cplusplus),所有内容都不会被破坏。

关于c++ - 什么时候使用 extern "C"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7996171/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com