c++ - 尝试使用 extern "C"在 C 中调用 C++ 方法,得到 "undefined reference to"对象的链接器错误

标签 c++ c linker-errors extern

<分区>

我正在尝试做的是从一个 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());
}

最佳答案

@HolyBlackCat 是对的,我的错误是我忘了定义 stat_MyClass。将以下行添加到 myclass.cpp 的顶部修复了所有问题。

MyClass MyClass::stat_MyClass;

当我只是编译独立文件时,错误并没有出现,所以在我添加外部代码之前,我没有考虑将我的精力集中在那些已经存在(或不存在)的东西上。谢谢!

关于c++ - 尝试使用 extern "C"在 C 中调用 C++ 方法,得到 "undefined reference to"对象的链接器错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59401416/

相关文章:

c++ - 静态库加载相关问题

c++ - 在具有低级别访问权限的随身碟上写入

C++ 取模除法

c - 为什么 uaccess.h 中的 access_ok 宏的实现没有使用它的所有参数?

c - 链接器错误 - typedef 结构

c++ - 在内存中创建进程 C++

assembly - Cygwin:重新定位被截断以适合 R_X86_64_32S 对 '.data'

c++ - 数组中有多个变量类型

c Valgrind 大小 4 的读取无效 -> 段错误

c - 如何在 LLDB 中设置 const char* 变量