所以我正在練習一個關于 Linux 的 C 專案的教程系列。為了創建 makefile,我按 CTR SHIFT P 進入 Palet,搜索 make 檔案,選擇正確的選項,然后選擇 C 專案。在教程中,該人將 make 檔案中的 src 更改為靜態路徑,即:pwd。那行得通。當他改回 src 并像他一樣將檔案移動到 src 檔案夾后,執行 make clean,然后 make,我得到了這個:
[termg@term-ms7c02 HelloWorldnonVR]$ make
g -std=c 11 -Wall -o obj/list.o -c src/list.cpp
g -std=c 11 -Wall -o obj/main.o -c src/main.cpp
g -std=c 11 -Wall -o HelloWorld obj/list.o obj/main.o
/usr/bin/ld: obj/main.o: in function `List::List()':
main.cpp:(.text 0x0): multiple definition of `List::List()'; obj/list.o:list.cpp:(.text 0x0): first defined here
/usr/bin/ld: obj/main.o: in function `List::List()':
main.cpp:(.text 0x0): multiple definition of `List::List()'; obj/list.o:list.cpp:(.text 0x0): first defined here
/usr/bin/ld: obj/main.o: in function `List::~List()':
main.cpp:(.text 0x2c): multiple definition of `List::~List()'; obj/list.o:list.cpp:(.text 0x2c): first defined here
/usr/bin/ld: obj/main.o: in function `List::~List()':
main.cpp:(.text 0x2c): multiple definition of `List::~List()'; obj/list.o:list.cpp:(.text 0x2c): first defined here
collect2: error: ld returned 1 exit status
make: *** [Makefile:37: HelloWorld] Error 1
[termg@term-ms7c02 HelloWorldnonVR]$
共有三個檔案。一個類及其標題,然后是主類。list.h 位于 src 的 include 子檔案夾中。我目前找不到有關此問題的任何資訊,因此將不勝感激。本教程在制作或運行檔案方面沒有任何問題。VSCode 擴展是 C/C Makefile 專案。我的系統是Manjaro。我確實做了清理并洗掉了makefile以重新開始,以防我敲擊鍵盤或其他東西但相同的結果仍然存在。從我所看到的來看,問題是沒有創建 HelloWorld 可執行檔案。HelloWorld 是模板中的應用名稱。
將問題縮小到標題。沒有建構式它可以作業,但有了它們它就不行。
#include <iostream>
#include <vector>
using namespace std;
class List
{
private:
/* data */
protected:
public:
void print_menu(); //Prototype
void print_list();
void add_item();
void delete_item();
vector<string> list;
string name;
//constructor
List(/* args */);
//destructor
~List();
};
List::List(/* args */)
{
}
List::~List()
{
}
關于造成這種情況的任何想法?
uj5u.com熱心網友回復:
如果您學習編譯器來解釋它,錯誤訊息會告訴您確切的問題是什么:
main.cpp:...: multiple definition of `List::List()'; obj/list.o:list.cpp:...: first defined here
這里是說你已經定義了兩次建構式:一次 inmain.cpp和一次 in list.cpp。
而且,在 99.99999% 的情況下,編譯器(在這種情況下技術上是聯結器)是正確的。main.cpp您已經在頭檔案中定義了建構式和解構式,并且在檔案和檔案中都包含了頭檔案list.cpp,因此建構式和解構式在兩者中都定義了,就像錯誤所說的那樣。
您需要將建構式和解構式放在list.cpp源檔案中,而不是放在頭檔案中。
或者,您可以將它們放在類本身中,這使它們行內,然后您就不會遇到這個問題:
class List
{
private:
/* data */
protected:
public:
List(/* args */) {}
~List() {}
void print_menu(); //Prototype
當然,這只有在它們足夠小且足夠簡單以像這樣行內時才有意義。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/445345.html
上一篇:三元運算子決定呼叫哪個成員函式
