简体   繁体   English

从C src调用C ++函数

[英]Calling C++ functions from a C src

I have mixed code base of C/C++ in a MS Visual Studio 2010 project and am trying to call a static function defined in C++ file from a C src file. 我在MS Visual Studio 2010项目中混合使用C / C ++代码库,并尝试从C src文件调用C ++文件中定义的静态函数。 Right now I get it to work by renaming the C src to CPP (ac -> a.cpp) Just wondering if there's a more graceful way of getting around it (turning some magic compiler flags on etc) without doing any large scale surgery to the code base(like using opaque pointers as suggested in this thread) 现在我通过将C src重命名为CPP来实现它(ac - > a.cpp)只是想知道是否有一种更优雅的方式绕过它(转换一些魔术编译器标志等)而不进行任何大规模的手术代码库(比如使用线程中建议的不透明指针)

Pls note my code base is pretty complex, I have created this small VS snippet to reproduce the error with bare minimum demonstrable code 请注意我的代码库非常复杂,我已经创建了这个小的VS片段,用最小的可证明的代码重现错误

ac AC

#include "b.h"

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

bh BH

#ifdef __cplusplus
extern "C" {
#endif

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

#ifdef __cplusplus
}
#endif

b.cpp b.cpp

#include "b.h"

#ifdef __cplusplus
extern "C" {
#endif

void B::func()
{
  return;
}

#ifdef __cplusplus
}
#endif

Error:- In MS Visual Studio 2010 错误: - 在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 : '}'

First, :: is not valid in C. 首先, ::在C中无效。

Second, including a header is equivalent to copy-pasting a .h file into your C file. 其次,包括标题相当于将.h文件复制粘贴到您的C文件中。 Your header must be valid C. Here's some deeper insight: 您的标题必须有效C.以下是一些更深入的见解:

How to call C++ function from C? 如何从C调用C ++函数?

Elegantly call C++ from C 优雅地从C调用C ++

Though, my alternative advice is, compile your C as C++. 虽然,我的另一个建议是,将C编译为C ++。 There's a chance it would take minimal or no work to turn out as valid C++. 有可能只需要很少或根本没有工作就可以成为有效的C ++。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM