簡體   English   中英

Windows中C ++編譯,Linux中多定義錯誤

[英]C++ Compiles in Windows, multiple definition error in Linux

首先,我說我不是最好的C ++,並且對Linux知之甚少。 對於一個班級項目,我們必須實現一個堆,因此我假設自己可以將文件上傳到學校擁有的Linux存儲庫中,所以我在Windows PC上編寫了所有代碼。 [也許這是我出問題的地方,而不能簡單地做到這一點。]我的代碼將編譯並清除Windows PC上提供的所有測試用例。 當我將文件上傳到Linux時,我創建了一個makefile,當我使用make命令時,我會得到一個包含多個定義錯誤的清單。 我正在使用的每個功能出現一個錯誤。 我已經進行了一些搜索,但是當我開始時,我更加困惑。

我的文件是:main.cpp,main.h,heap.cpp,heap.h,util.cpp和util.h。

我認為問題出在我的include語句上,但我不確定100%。

這是文件的示例。

main.cpp中

 #include <iostream>  //needed to use basic inputs/outputs
 #include <stdio.h>
 #include <stdlib.h>
 #include "main.h"
 #include "util.cpp"
 #include "heap.cpp"
 #include <fstream>
 using namespace std;

main.h為空白。

heap.cpp

 #include <iostream>  //needed to use basic inputs/outputs
 #include <stdio.h>
 #include <stdlib.h>
 #include "heap.h"
 #include <cmath>
 #include <math.h>
 using namespace std;

 //expanded functions found in the heap.h file

heap.h

 //2 structs
 //9 functions

util.cpp

 #include <iostream>  //needed to use basic inputs/outputs
 #include <stdio.h>
 #include <stdlib.h>
 #include "util.h"
 using namespace std;

 //expanded functions found in util.h

util.h

 //1 function

在heap.h和util.h之間,我有10個函數,運行make命令后,我會得到關於所有十個函數的警告:

 multiple definition of 'FUNCTIONNAME'
 main.o:main.cpp:(.text+0x1b7): first defined here

我假設0x1b7是一個內存位置,因為它們各不相同。

任何幫助將不勝感激。

您尚未顯示Makefile,但很可能它包含此規則或類似規則

program: main.o heap.o util.o
    $(CXX) $(CXXFLAGS) -o program main.o heap.o util.o

現在發生了什么,編譯器將構建三個目標文件main.o,heap.o和util.o。 接下來,將目標文件鏈接在一起以構建program

鏈接器可以看到main.o和heap.o或main.o和util.o中定義的各種函數的定義。 這就是為什么它抱怨“'FUNCTIONNAME'的多個定義”


為什么對這些功能進行了多次定義?

將文件包含到另一個源中時,就好像您將內容復制到#include的位置。 這意味着在heap.cpp中定義的函數:

void create_heap(int size)
{
    // create a heap ...
}

逐字復制到main.cpp中,該行

#include "heap.cpp"

是。


因為heap.cpp具有create_heap()的定義,並且main.cpp #include是heap.cpp的內容,所以它們都包含自己的create_heap()副本。 現在,您可以編譯heap.o和main.o,並將它們鏈接在一起。 每個目標文件都有一個create_heap()副本,這是鏈接器感到困惑和抱怨的地方

multiple definition of 'create_heap'
main.o:main.cpp:(.text+0x1b7): first defined here

要解決此問題,只需替換包含cpp源的行,例如

#include "util.cpp"
#include "heap.cpp"

及其各自的頭文件

#include "util.h"
#include "heap.h"

僅保留與main.cpp相關的函數定義,除此之外別無其他。 現在main.cpp沒有屬於util.cpp或heap.cpp的函數定義,並且鏈接器錯誤也消失了。


據推測,這在Windows上可行,因為項目文件中僅包含main.cpp,因此所生成的可執行文件中只有一個定義(來自main.o)。

如果您已包括Linux Makefile中的所有源,則在Windows中也可能會看到該錯誤。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM