开发者社区> 问答> 正文

尝试使用extern“C”在C中调用C++方法,得到“未定义引用”对象[重复]的链接错误

我是什么试着要做的就是从C文件中调用一个C++方法,在一个新的、但相当大的代码库中。我已经从代码库的其他地方复制了一个实现,但是当我试图构建它时,我会得到链接器错误。

我想我正在做的是在.cpp/.h文件对中创建一个类。在全局头文件中,我声明了一个包装函数,在.cpp文件中,我在外“C”让它调用类的方法之一。然后从我的主.c文件调用包装函数。

我是什么其实做错事。在过去的几个小时里,我一直在阅读类似的堆栈溢出错误以及如何外“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());
}

展开
收起
aqal5zs3gkqgc 2019-12-19 20:48:34 4314 0
1 条回答
写回答
取消 提交回答
  • 是对的,我的错误是我忘了定义STAT_MyClass。将下面的行添加到myclass.cpp的顶部,可以修复所有问题。

    MyClass MyClass::stat_MyClass; 当我只是编译独立文件时,错误并没有出现,所以在我加入外挂代码之前,我不想把精力集中在(或不在)那些东西上。谢谢!

    2019-12-19 20:49:13
    赞同 展开评论 打赏
问答分类:
C++
问答地址:
问答排行榜
最热
最新

相关电子书

更多
使用C++11开发PHP7扩展 立即下载
GPON Class C++ SFP O;T Transce 立即下载
GPON Class C++ SFP OLT Transce 立即下载