我有点像这里描述的逆问题: Combining C++ and C - how does #ifdef __cplusplus work?
整个应用程序都是用 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
我试过:
#ifdef __cplusplus
extern "C" {
#endif
<C code>
#ifdef __cplusplus
}
#endif
但它显示相同的错误。
我正在做的是在 C 文件中包含一个 C++ header ,其中包含我需要的外部函数。
例子:
求解器.c
#include "HarpBuffers.h"
...
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();
最佳答案
您的函数声明应该在 extern "C"
block 中,并且 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
(函数默认具有外部链接;无需在标题中添加困惑。)
求解器.c:
#include "HarpBuffers.h"
/* Use functions */
HarpBuffers.cpp:
#include "HarpBuffers.h"
// Define functions
关于c++ - 将 C++ 代码放入 C 时未定义对 `function()' 的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48841307/