Undefined Reference to

后端 未结 6 904
生来不讨喜
生来不讨喜 2020-12-01 06:28

When I compile my code for a linked list, I get a bunch of undefined reference errors. The code is below. I have been compiling with both of these statements:



        
相关标签:
6条回答
  • 2020-12-01 07:03

    I was getting this error because my cpp files was not added in the CMakeLists.txt file

    0 讨论(0)
  • 2020-12-01 07:06
    1. Usually headers guards are for header files (i.e., .h ) not for source files ( i.e., .cpp ).
    2. Include the necessary standard headers and namespaces in source files.

    LinearNode.h:

    #ifndef LINEARNODE_H
    #define LINEARNODE_H
    
    class LinearNode
    {
        // .....
    };
    
    #endif
    

    LinearNode.cpp:

    #include "LinearNode.h"
    #include <iostream>
    using namespace std;
    // And now the definitions
    

    LinkedList.h:

    #ifndef LINKEDLIST_H
    #define LINKEDLIST_H
    
    class LinearNode; // Forward Declaration
    class LinkedList
    {
        // ...
    };
    
    #endif
    

    LinkedList.cpp

    #include "LinearNode.h"
    #include "LinkedList.h"
    #include <iostream>
    using namespace std;
    
    // Definitions
    

    test.cpp is source file is fine. Note that header files are never compiled. Assuming all the files are in a single folder -

    g++ LinearNode.cpp LinkedList.cpp test.cpp -o exe.out
    
    0 讨论(0)
  • 2020-12-01 07:06

    Another way to get this error is by accidentally writing the definition of something in an anonymous namespace:

    foo.h:

    namespace foo {
        void bar();
    }
    

    foo.cc:

    namespace foo {
        namespace {  // wrong
            void bar() { cout << "hello"; };
        }
    }
    

    other.cc file:

    #include "foo.h"
    
    void baz() {
        foo::bar();
    }
    
    0 讨论(0)
  • 2020-12-01 07:08
    g++ test.cpp LinearNode.cpp LinkedList.cpp -o test
    
    0 讨论(0)
  • 2020-12-01 07:22

    I had this issue when I forgot to add the new .h/.c file I created to the meson recipe so this is just a friendly reminder.

    0 讨论(0)
  • 2020-12-01 07:23

    Try to remove the constructor and destructors, it's working for me....

    0 讨论(0)
提交回复
热议问题