gpt4 book ai didi

c++ - 从 C src 调用 C++ 函数

转载 作者:搜寻专家 更新时间:2023-10-31 00:28:41 24 4
gpt4 key购买 nike

我在 MS Visual Studio 2010 项目中混合了 C/C++ 的代码库,并试图从 C src 文件调用 C++ 文件中定义的静态函数。现在我通过将 C src 重命名为 CPP (a.c -> a.cpp) 来让它工作 只是想知道是否有更优雅的方式来绕过它(打开一些神奇的编译器标志等)而无需进行任何大规模手术代码库(比如使用 this 线程中建议的不透明指针)

请注意我的代码库非常复杂,我创建了这个小的 VS 代码片段以使用最少的可演示代码重现错误

a.c

#include "b.h"

void test()
{
B::func();
}

b.h

#ifdef __cplusplus
extern "C" {
#endif

class B{
public:
static void func();
};

#ifdef __cplusplus
}
#endif

b.cpp

#include "b.h"

#ifdef __cplusplus
extern "C" {
#endif

void B::func()
{
return;
}

#ifdef __cplusplus
}
#endif

错误:- 在 MS Visual Studio 2010 中

1>c:\.....\b.h(5): error C2061: syntax error : identifier 'B'
1>c:\.....\b.h(5): error C2059: syntax error : ';'
1>c:\.....\b.h(5): error C2449: found '{' at file scope (missing function header?)
1>c:\.....\b.h(8): error C2059: syntax error : '}'

最佳答案

首先,:: 在 C 中是无效的。

其次,包含 header 相当于将 .h 文件复制粘贴到您的 C 文件中。您的 header 必须是有效的 C。这里有一些更深入的见解:

How to call C++ function from C?

Elegantly call C++ from C

不过,我的替代建议是将 C 编译为 C++。有可能只需要很少的工作或不需要任何工作就可以变成有效的 C++。

关于c++ - 从 C src 调用 C++ 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44273627/

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