<分区>
我正在尝试做的是从一个 C 文件中调用一个 C++ 方法,在一个对我来说很新但相当大的代码库中。我从代码库的其他地方抄袭了一个实现,但在尝试构建它时遇到链接器错误。
我认为我正在做的是在 .cpp/.h 文件对中创建一个类。在全局头文件中,我声明了一个包装函数,在 .cpp 文件中,我在 extern "C" 中定义了该包装函数,并让它调用类的方法之一。然后我从我的主 .c 文件中调用包装函数。
我实际上做的是错误的。在过去的几个小时里,我一直在阅读类似的 stackoverflow 错误以及 extern "C" 的工作原理,但我仍然不明白哪里出了问题。我在这里做的事情有明显的错误吗?
我对自己对该项目构建系统的设置方式的理解没有信心,但我通常相信它设置正确,并且我已将 myclass.cpp 添加到正确的构建目标列表中。所以我认为错误可能出在下面的某个地方。
错误信息:
Creating objlist.lnk...
Linking into output.elf
module.o: In function `MyClass::MyMethod()':
~/myclass.cpp:5: undefined reference to `MyClass::stat_MyClass'
~/myclass.cpp:5: undefined reference to `MyClass::stat_MyClass'
module.o:~/myclass.cpp:5: more undefined references to `MyClass::stat_MyClass' follow
collect2: error: ld returned 1 exit status
make[1]: *** [output.elf] Error 1
make: *** [default] Error 2
释义代码:
全局.h
#ifdef __cplusplus
extern "C" {
#endif
int my_c_wrapper_func(void);
// other function declarations
#ifdef __cplusplus
}
#endif
全局.c
#include "global.h"
// my_c_wrapper_func() not defined here
// other function definitions
我的类.h
#include "global.h"
class MyClass {
public:
static MyClass* get() { return &stat_MyClass; } // Get the singleton
int MyMethod();
private:
static MyClass stat_MyClass; // The singleton
}
我的类.cpp
#include "myclass.h"
extern "C" int my_c_wrapper_func() {
return MyClass::get()->MyMethod();
}
int MyClass::MyMethod() {
return 1;
}
主.c
#include "global.h"
int main() {
return(my_c_wrapper_func());
}