7

Can't seem to get the errors to go away. Errors are below. I have looked on google and still can't figure it out. It is not like I am new to Cpp, but have not fooled with it in a while.

Weird thing is it worked with G++ in Windows...

Errors:

  • [ze@fed0r! ---**__*]$ g++ main.cpp
  • /tmp/ccJL2ZHE.o: In function `main':
  • main.cpp:(.text+0x11): undefined reference to `Help::Help()'
  • main.cpp:(.text+0x1d): undefined reference to `Help::sayName()'
  • main.cpp:(.text+0x2e): undefined reference to `Help::~Help()'
  • main.cpp:(.text+0x46): undefined reference to `Help::~Help()'
  • collect2: ld returned 1 exit status

main.cpp

#include <iostream>
#include "Help.h"

using namespace std;

int main () {

    Help h;
    h.sayName();

    // ***

    // ***

    // ***
    return 0;

}

Help.h

#ifndef HELP_H
#define HELP_H

class Help {
    public:
        Help();
        ~Help();
        void sayName();
    protected:
    private:
};

#endif // HELP_H

Help.cpp

#include <iostream>
#include "Help.h"

using namespace std;

Help::Help() { // Constructor
}

Help::~Help() { // Destructor
}

void Help::sayName() {
    cout << "            ***************" << endl;
    cout << "   ************************************" << endl;
    cout << "              ************" << endl;
    cout << "         *********************" << endl;
}
4

3 回答 3

15

g++ main.cpp Help.cpp

您必须告诉编译器您希望它编译的所有文件,而不仅仅是第一个文件。

于 2011-08-08T05:59:33.753 回答
8

您应该将 help.o 添加到您的 g++ 行:

g++ -c help.cpp -o help.o
g++ help.o main.cpp

通过将其分成两行,您可以节省编译时间(对于较大的项目),因为您help.cpp只能在更改时进行编译。makeMakefile得好会省去很多麻烦:

#Makefile
all: main

main: help main.cpp
    g++ -o main help.o main.cpp

help: help.cpp
    g++ -c -o help.o help.cpp
于 2011-08-08T06:00:36.367 回答
0

我的 Linux Lubuntu 发行版也有同样的问题,它给我的构造函数析构函数造成了问题,它无法识别它们。

实际上,如果您只是将所有三个文件编译在一起,就会发生这种情况。因此,一旦您保存了所有文件,只需执行以下操作:

$ g++ main.cpp Help.h Help.cpp
$ ./a.out

./a.out 是 Linux 的可执行文件,对不起,我不知道 Windows。您的程序将运行顺利。

于 2018-08-24T09:47:59.813 回答