"undefined reference to" in G++ Cpp

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;
    }
    

    g++ main.cpp Help.cpp

    You have to tell the compiler all the files that you want it to compile, not just the first one.


    You should add help.o to your g++ line:

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

    By splitting it to two lines you can save compilation time (in case of larger projects), because you can compile help.cpp only when it was changed. make and Makefile used well will save you a lot of headache:

    #Makefile
    all: main
    
    main: help main.cpp
        g++ -o main help.o main.cpp
    
    help: help.cpp
        g++ -c -o help.o help.cpp
    
    链接地址: http://www.djcxy.com/p/51560.html

    上一篇: 无法链接GLFW3:未定义的引用

    下一篇: “未定义的引用”在G ++ Cpp中