将C++代码放在C中时未定义引用`function()'

tes*_*n3r 0 c c++ linker precompiled-headers

我有一个如下所述的反问题: 结合C++和C - #ifdef __cplusplus如何工作?

整个应用程序是C代码,现在我需要在那里添加一些C++函数.但在这样做时我得到了这个错误:

/tmp/cczmWtaT.o: In function `aocl_utils::_checkError(int, char const*, int, char const*, ...)':
/home/harp/host/../common/src/AOCLUtils/opencl.cpp:245: undefined reference to `cleanup()'
/tmp/ccrmKQaT.o: In function `main':
/home/harp/host/src/main.c:165: undefined reference to `harp_setup()'
/tmp/ccGKataf.o: In function `solver_propagate(solver_t*)':
/home/harp/host/src/solver.c:751: undefined reference to `launch_kernel()'
collect2: error: ld returned 1 exit status
Run Code Online (Sandbox Code Playgroud)

我试过了:

#ifdef __cplusplus
extern "C" {
#endif

<C code>

#ifdef __cplusplus
}
#endif
Run Code Online (Sandbox Code Playgroud)

但它显示了同样的错误.

我正在做的是在C文件中包含一个C++头文件,其中包含我需要的外部函数.

例:

solver.c

#include "HarpBuffers.h"
...
Run Code Online (Sandbox Code Playgroud)

HarpBuffers.h

extern void harp_setup();
extern void setup_buffers(cl_int a, cl_int b, int **h_clause, unsigned int **h_assigns, int **h_target);

extern void launch_kernel();
extern void cleanup();
Run Code Online (Sandbox Code Playgroud)

mol*_*ilo 5

您的函数声明应该在一个extern "C"块内,并且在遇到函数的定义之前必须由C++编译器看到它们.

(该extern "C"是什么使C++编译器不裂伤的函数的名称.
#ifdef __cplusplus使得代码不可见的一个C编译器.)

像这样:

HarpBuffers.h:

#ifdef __cplusplus
extern "C" {
#endif

void harp_setup();
void setup_buffers(cl_int a, cl_int b, int **h_clause, unsigned int **h_assigns, int **h_target);

void launch_kernel();
void cleanup();

#ifdef __cplusplus
}
#endif
Run Code Online (Sandbox Code Playgroud)

(默认情况下,函数具有外部链接;不需要在标题中添加混乱.)

solver.c:

#include "HarpBuffers.h"
/* Use functions */
Run Code Online (Sandbox Code Playgroud)

HarpBuffers.cpp:

#include "HarpBuffers.h"
// Define functions
Run Code Online (Sandbox Code Playgroud)