This question already has answers here:
What is an undefined reference/unresolved external symbol error and how do I fix it?
                                
                                    (32个答案)
                                
                        
                                3年前关闭。
            
                    
我看过其他类似的问题,但我对答案的理解并不十分清楚。我收到此错误:

在函数main':C:/Users/Danny/ClionProjects/LinkedList/main.cpp:9: undefined reference to linkList :: linkList()'中
collect2.exe:错误:ld返回1退出状态

linkList.cpp:

#include <iostream>
#include <cstdlib>
#include "linkList.h"

using namespace std;

linkList::linkList()
{
    head = NULL;
    follow = NULL;
    trail = NULL;
}

void linkList::addNode(int dataAdd)
{
    nodePtr n = new node;
    n->next = NULL;
    n->data = dataAdd;

    if (head != NULL)
    {
        follow = head;
        while (follow->next != NULL)
        {
            follow = follow->next;
        }
    }
    else
    {
        head = n;
    }

}

void linkList::deleteNode(int nodeDel)
{
    nodePtr delPtr = NULL;
    follow = head;
    trail = head;

    while(follow != NULL)
    {
        trail = follow;
        follow = follow->next;
        if (follow->data == nodeDel)
        {
            delPtr = follow;
            follow = follow->next;
            trail->next = follow;
            delete delPtr;
        }
        if(follow == NULL)
        {
            cout << delPtr << " was not in list\n";
            delete delPtr; // since we did not use delPtr we want to delete it to make sure it doesnt take up memory
        }

    }

}

void linkList::printList()
{
    follow = head;
    while(follow != NULL)
    {
        cout << follow->data << endl;
        follow = follow->next;
    }


}


LinkList.h:

struct node {
    int data;
    node* next;
};

typedef struct node* nodePtr;


class linkList
{ // the linkList will be composed of nodes

private:
    nodePtr head;
    nodePtr follow;
    nodePtr trail;

public:
    linkList();
    void addNode(int dataAdd);
    void deleteNode(int dataDel);
    void printList();
};


main.cpp:

#include <cstdlib>
#include "linkList.h"


using namespace std;

int main() {

    linkList myList;


    return 0;
}


我知道这与文件链接方式有关,当我在主文件中将#include linkList.h更改为#include linkList.cpp时,为什么可以正常工作?我有另一个类似的程序,它是一个二进制搜索树,可以很好地工作并且设置类型基本相同。所以我的问题是如何解决?为什么会这样呢?

最佳答案

如果您正在使用自动执行的构建系统/ IDE,则需要将linkList.cpp添加到项目中。您需要:


g++ -c linkList.cpp -o linkList.o单独编译
然后编译并链接最终的可执行文件g++ main.cpp linkList.o


或直接编译它们(不适用于较大的项目):g++ main.cpp linkList.cpp

包含.cpp文件是一个坏主意,您不必这样做。

10-06 01:04