使用 &MyClass::MyFunction 时出现未定义的引用链接错误
这只是让我难住了,所以我想我应该在这里查询:
我有一个类如下:
class MyClass {
public:
void myThreadFunc();
};
那是在标题中。在构造函数中
MyClass::MyClass() {
...
boost::thread t(boost::bind(&MyClass::myThreadFunc, this));
...
}
正如我所看到的那样。没有编译时错误。但是,当我链接如下时:
g++ -o test.exe main.o MyClass.o /*specify boost and other libraries */
我得到:
MyClass.o:MyClass.cpp:(.text+0xa4): undefined reference to `MyClass::myThreadFunc()'
collect2: ld returned 1 exit status
这没有任何意义。让我特别奇怪的是,这是一个链接器错误。我包含了两个目标文件。
谁能告诉我发生了什么事吗?如果可能相关的话,我在 Windows 上使用 MinGW。
编辑:
史诗般的失败。在我的 cpp 文件中定义函数时,我忘记了 MyClass:: 前缀。我只是没有决定检查一下。几乎和在类定义后忘记分号一样糟糕。
this just has me stumped, so I thought I'd query here:
I have a class as follows:
class MyClass {
public:
void myThreadFunc();
};
That's in the header. In the constructor
MyClass::MyClass() {
...
boost::thread t(boost::bind(&MyClass::myThreadFunc, this));
...
}
As I've seen done. There are NO compile time errors. However, when I link as follows:
g++ -o test.exe main.o MyClass.o /*specify boost and other libraries */
I get:
MyClass.o:MyClass.cpp:(.text+0xa4): undefined reference to `MyClass::myThreadFunc()'
collect2: ld returned 1 exit status
Which doesn't make any sense. What strikes me especially odd is that's its a linker error. I included both of my object files.
Can anyone tell me what's going on? If it might be relevant, I'm on MinGW on Windows.
EDIT:
Epic fail. I forgot the MyClass:: prefix when defining the function in my cpp file. I just didn't decide to check that. Almost as bad as forgetting a semicolin after a class definition.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要在某处为
MyClass::myThreadFunc()
编写函数体。为MyClass
编写构造函数与实现MyClass::myThreadFunc()
成员函数不同。如果你在 C/C++ 中调用一个函数,它必须在某处有一个函数体。这就是为什么它是一个链接器错误;它试图在所有可用的目标文件中找到函数体,但你没有编写一个,所以它不能。
You need to write a function body for
MyClass::myThreadFunc()
somewhere. Writing a constructor forMyClass
is different from implementing theMyClass::myThreadFunc()
member function.If you call a function in C/C++, it must have a function body somewhere. That's why it's a linker error; it's trying to find the function body in all of the available object files, but you didn't write one so it can't.