【问题标题】:Undefined reference to member function (C++)对成员函数的未定义引用 (C++)
【发布时间】:2012-12-02 01:39:33
【问题描述】:

我正在使用 Makefile 编译 C++ 项目,我收到一个未定义的引用错误,我怀疑这是一个简单的错误。

错误本身是:

$ make
g++ -c main.cpp
g++ -o p5 main.o
main.o:main.cpp:(.text+0x241): undefined reference to `Instructions::processInput(std::basic_string<char, std::char_traits<char>, std::allocator<char> >)'
collect2: ld returned 1 exit status
Makefile:2: recipe for target `p5' failed
make: *** [p5] Error 1

以下是项目中与错误有关的部分(为清楚起见): 我的makefile:

p5: main.o Instructions.o
    g++ -o p5 main.o

main.o: main.cpp Instructions.h
    g++ -c main.cpp

Instructions.o: Instructions.h Instructions.cpp
    g++ -c Instructions.cpp

我的 main.cpp 文件:

#include <string>
#include "Instructions.h"
using namespace std;

int main() {
    Instructions inst;
    inst.processInput("some string par example"); //THIS LINE HERE GIVES ME ERRORS
    return 0;
}

我的说明头文件:

#ifndef INSTRUCTIONS_H
#define INSTRUCTIONS_H
#include <string>

class Instructions {
public:
    Instructions() {input = ""; command = 0; xCoord = 0.0; yCoord = 0.0;};
    void processInput(std::string in);
private:
    std::string input;
    int command;
    double xCoord;
    double yCoord;
};
#endif

最后是 .cpp 文件,目前非常简单:

#include "Instructions.h"
#include <string>
#include <iostream>
using namespace std;

void Instructions::processInput(string in) {
    cout << "Processing: " << input << endl;
}

我一直在寻找解决方案,但无济于事。如果它确实在其他地方,请原谅我!我也希望它可以帮助所有还在使用 C++ 的初学者!

【问题讨论】:

  • 也许它认为“some string par example”意味着一个 char* 而不是一个字符串,所以你真正调用的是 processInput(char*) 而不是 processInput(string)。在这种情况下,请尝试执行 processInput(string("helloimastring"))
  • 嘿,@ForgiveMeI'mAN00b,我试过了,虽然它应该编译,但它给了我同样的错误。我认为这是因为虽然语法正确,但问题是一样的。
  • 奇怪,很抱歉,虽然这是我能做的最好的帮助,但我自己还没有完全掌握与编译有关的所有内容......:|

标签: c++ object initialization undefined-reference


【解决方案1】:

请试试这个 Makefile :

 p5: Instructions.o main.o
     g++ Instructions.o main.o -o p5 

 Instructions.o: Instructions.cpp
     g++ -c Instructions.cpp -o Instructions.o 

 main.o: main.cpp Instructions.h
     g++ -c main.cpp Instructions.o -o main.o

要编译p5,首先需要编译它的所有依赖项,即Instructions.omain.oInstructions.o是独立的,所以可以像g++ -c Instructions.cpp这样编译。但是main.o 依赖于类Instructions 所以它依赖于它的.o 它应该像这样编译g++ -c main.cpp Instructions.o

p5 也是一样,它需要所有的*.o

【讨论】:

  • 嗨!不幸的是,这也不起作用,但它引起了我对 makefile 知识的怀疑。那么,在制作新的 .o 文件时,是否必须提供 .o 文件而不是 .header 文件?
  • 这个怎么样?我在末尾添加了Instructions.o ...请检查
  • 嗯,它会引发相同的编译器错误。不过感谢您的帮助,我很感激!
  • 我修改了makefile,请检查错误信息是否改变?
  • 嘿,这似乎奏效了!这是什么意思?编译器需要特定的文件制作顺序吗?主要文件接近尾声?
猜你喜欢
  • 2011-11-04
  • 2017-05-27
  • 2019-04-29
  • 2012-03-10
  • 1970-01-01
  • 1970-01-01
  • 2013-11-06
  • 2011-05-07
  • 2012-12-20
相关资源
最近更新 更多