【问题标题】:Trying to call C++ method in C using extern "C", get a linker error of "undefined reference to" object [duplicate]尝试使用 extern“C”在 C 中调用 C++ 方法,得到“未定义引用”对象的链接器错误 [重复]
【发布时间】:2019-12-18 23:31:21
【问题描述】:

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

【问题讨论】:

  • static MyClass stat_MyClass 是静态变量的声明。您还需要一个定义。
  • 这能回答你的问题吗? Initialize static variables in C++ class?this one?
  • @HolyBlackCat 你完全正确,那是我的愚蠢错误。将“MyClass MyClass::stat_MyClass”添加到我的 .cpp 文件的顶部可以解决所有问题。当我刚刚编译文件时,该错误没有出现,所以在我添加外部代码之前,我没有考虑将精力集中在那些存在(或不存在)的东西上。谢谢!

标签: c++ c linker-errors extern


【解决方案1】:

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

MyClass MyClass::stat_MyClass;

当我刚刚编译独立文件时,该错误并未出现,因此我没有考虑将精力集中在添加外部代码之前存在(或不存在)的内容上。谢谢!

【讨论】:

    猜你喜欢
    • 2013-01-11
    • 2021-07-18
    • 2014-02-13
    • 2015-11-25
    • 2013-04-01
    • 1970-01-01
    • 2016-07-21
    • 1970-01-01
    相关资源
    最近更新 更多