gpt4 book ai didi

c++ - 在库中包含具有外部 C 链接的函数

转载 作者:太空宇宙 更新时间:2023-11-04 07:38:39 26 4
gpt4 key购买 nike

我在 C++ 代码中包含了一些带有 extern c 链接的 C 函数。例如。

// File Y.cpp: 

extern C {
void fnA(void) { }
void fnB(void* a, void* b) { }
}

class test {
....
};

// end of file

文件 Y 在模块 Mod 下。在为模块 Mod 构建库 libMod-O.a 时,我没有看到包含在 extern block 下的函数,除非 Y.h 包含在其他文件 (Mod.cpp) 中并且使用了类测试。因此,除非我在 Mod.cpp 中创建测试类的对象,否则我在 libMod-O.a 中看不到外部函数(fnA、fnB),即使在构建 libMod-O.a 期间编译了 Y.cpp。这样做的结果是当另一个模块使用 fnA、fnB 时发生链接器错误。

我没有看到包含的外部函数 fnA 和 fnB 与 Mod.cpp 中类测试的使用之间的联系。这是预期的还是有更好的方法来定义它?

最佳答案

当然是指 extern "C"。

您需要将 C 代码和 C++ 代码完全分开。

在 YourCCode.h 中:

#ifdef __cplusplus
extern "C" {
#endif

void fnA(void);
void fnB(void* a, void* b);

#ifdef __cplusplus
}
#endif

在 YourCCode.c 中:

void fnA(void) {}
void fnB(void* a, void* b) {}

确保您的编译器将 YourCCode.c 编译为 C,而不是 C++。

在你的 C++ 代码中

#include "YourCCode.h"

fnA();
// etc.

关于c++ - 在库中包含具有外部 C 链接的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6432781/

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