从 C 程序调用 C++ 函数

Calling a C++ Function from C Program

我正在努力将用 C++ 编写的函数添加到用 C 编写的大型程序中。

我试图将 C 程序中包含的所有代码包围在 extern "C" 块中,但是当我使用 g++ 进行编译时,我仍然会收到编译器试图将 C 编译为 C++ 的错误。我已将 extern "C" 块添加到所有 headers 和 .c 文件中,如下所示:

#ifdef __cplusplus
extern "C"
{
#endif

//C code here

#ifdef __cplusplus
}
#endif

错误如下所示:

./sortcodes/oci.c: In function ‘int GetSpecList(ClientData, Tcl_Interp*, int, Tcl_Obj* const*)’: ./sortcodes/oci.c:188:25: error: ‘init’ does not name a type static init=TRUE;

如果我删除我的 C++ 函数调用并仅使用 gcc 编译 C 程序,则不会发生这些错误。

如果我删除 extern "C" 块并使用选项编译

gcc -std=c++0x -lstdc++ -std=c++11

我收到类似下面的错误,其中 C++ 标志显然被忽略了

./Event_Reader.cpp:9:20: fatal error: iostream: No such file or directory #include

是否有任何我遗漏或误解的选项?如有任何建议,我们将不胜感激。

首先,要编译 c++ 代码,您必须使用 g++ 或 clang++ 等 c++ 编译器。然后,您需要使用 extern "C" 链接声明所需的 c++ 函数。此时您可以从 C 代码调用该函数。 具体例子参考How do I call a C++ function from C