我正在[[尝试要做的是在一个新的但相当大的代码库中,从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
global.h反义代码:
#ifdef __cplusplus
extern "C" {
#endif
int my_c_wrapper_func(void);
// other function declarations
#ifdef __cplusplus
}
#endif
global.c
#include "global.h"
// my_c_wrapper_func() not defined here
// other function definitions
myclass.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
}
myclass.cpp
#include "myclass.h"
extern "C" int my_c_wrapper_func() {
return MyClass::get()->MyMethod();
}
int MyClass::MyMethod() {
return 1;
}
main.c
#include "global.h"
int main() {
return(my_c_wrapper_func());
}
[我想做的是在一个新的但相当大的代码库中,从C文件中调用C ++方法。我从代码库的其他地方抄袭了一个实现,但是正在获得链接器...