0

我正在使用 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

以下是与错误有关的项目部分(为清楚起见):我的生成文件:

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++ 的初学者!

4

1 回答 1

2

请试试这个 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.o. Instructions.o是独立的,所以可以这样编译g++ -c Instructions.cpp。但是main.o依赖于类Instructions所以它依赖于.o它应该像这样编译g++ -c main.cpp Instructions.o

同样的事情p5,它需要所有的*.o

于 2012-12-02T01:44:06.400 回答