我正在用 C 做一些鏈表實踐,并為單鏈表創建了一個簡單的類。當我嘗試在主程式中包含頭檔案時,我得到一個未定義的參考錯誤。如果我包含 .cpp 檔案,它會按我的意愿作業。
自從我上次用 C 撰寫代碼以來已經有一段時間了,而且我無法為我的愛找出問題所在。一些幫助將不勝感激。我正在使用帶有 git-bash 介面和 g -std=c 11 的 Windows Termnial。代碼包含在下面!
//The main file .cpp
#include "SingleNode.h"
int main() {
SingleNode* tail = new SingleNode(2);
SingleNode* head = new SingleNode(1, tail);
head->print();
return 0;
}
//SingleNode.h
#ifndef SINGLENODE_H
#define SINGLENODE_H
class SingleNode {
public:
int val;
SingleNode* next;
SingleNode();
SingleNode(int x);
SingleNode(int x, SingleNode* next);
void print();
};
#endif
//SingleNode.cpp
#include "SingleNode.h"
#include <iostream>
using namespace std;
SingleNode::SingleNode() : val(0), next(nullptr) {}
SingleNode::SingleNode(int x) : val(x), next(nullptr) {}
SingleNode::SingleNode(int x, SingleNode* next) : val(x), next(next) {}
void SingleNode::print() {
if (this->next != nullptr) {
cout<<this->val<<"->";
this->next->print();
} else {
cout<<this->val<<"->"<<"null"<<endl;
}
}
運行時:
$ g -std=c 11 LinkedList.cpp -o LinkedList.exe
C:\AppData\Local\Temp\ccEbmcRt.o:LinkedList.cpp:(.text 0x30): undefined reference to `SingleNode::SingleNode(int)'
C:\AppData\Local\Temp\ccEbmcRt.o:LinkedList.cpp:(.text 0x59): undefined reference to `SingleNode::SingleNode(int, SingleNode*)'
C:\AppData\Local\Temp\ccEbmcRt.o:LinkedList.cpp:(.text 0x69): undefined reference to `SingleNode::print()'
collect2.exe: error: ld returned 1 exit status
如果我改為#include "SingleNode.cpp"它作業正常。
uj5u.com熱心網友回復:
您包含頭檔案,因此原型可用,并且編譯器不會抱怨。聯結器需要找到與這些函式關聯的源。使用g -std=c 11 LinkedList.cpp -o LinkedList.exe編譯意味著您只使用主檔案源而不是包含鏈接串列實作的其他檔案。
解決方案是將SingleNode.cpp檔案也傳遞給編譯器。因此:
g -std=c 11 LinkedList.cpp SingleNode.cpp -o LinkedList.exe并將SingleNode.h檔案包含在LinkedList.cpp.
該#include指令執行文本替換,這意味著當您包含.cpp檔案(進而包含頭檔案)時,您將擁有一個包含兩個源檔案所需源的最終翻譯單元。
另請參閱:為什么我不應該包含 cpp 檔案而使用標頭?
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/425953.html
