2011-04-21 65 views
0

我想在linux中編譯一個簡單的應用程序。我的main.cpp看起來像在Linux中編譯C++

#include <string> 
#include <iostream> 
#include "Database.h" 

using namespace std; 
int main() 
{ 
    Database * db = new Database(); 
    commandLineInterface(*db); 
    return 0; 
} 

其中Database.h是我的頭並有一個相應的Database.cpp。編譯時出現以下錯誤:

[email protected]:~/code$ g++ -std=c++0x main.cpp -o test 
/tmp/ccf1PF28.o: In function `commandLineInterface(Database&)': 
main.cpp:(.text+0x187): undefined reference to `Database::transducer(std::basic_string<char, std::char_traits<char>, std::allocator<char> >)' 
main.cpp:(.text+0x492): undefined reference to `Database::transducer(std::basic_string<char, std::char_traits<char>, std::allocator<char> >)' 
main.cpp:(.text+0x50c): undefined reference to `Database::transducer(std::basic_string<char, std::char_traits<char>, std::allocator<char> >)' 
/tmp/ccf1PF28.o: In function `main': 
main.cpp:(.text+0x721): undefined reference to `Database::Database()' 
collect2: ld returned 1 exit status 

搜索類似這樣的東西遍佈整個地方,你可以想象得到。對於我可以做些什麼來解決問題有什麼建議?

+1

我想我們需要看看Database。(h | cpp)文件,或者至少是'Database'類和'commandLineInterface'接口/實現。 – 2011-04-21 15:05:21

回答

5

那些是鏈接器錯誤。它抱怨,因爲它試圖產生最終的可執行文件,但它不能,因爲它沒有用於Database函數的目標代碼(編譯器不推斷對應於Database.h的函數定義存在於Database.cpp中)。

試試這個:

g++ -std=c++0x main.cpp Database.cpp -o test 

或者:

g++ -std=c++0x main.cpp -c -o main.o 
g++ -std=c++0x Database.cpp -c -o Database.o 
g++ Database.o main.o -o test 
+0

我懷疑這一點,但不確定。現在我的數據庫類有其他包含等等。當然有一種方法可以編譯所有內容,而無需每次都輸入它?腳本還是有g ++選項? – Pete 2011-04-21 15:16:34

+1

@Pete - 你想要一個make文件。 http://www.gnu.org/software/make/manual/make.html或者使用將爲您的項目創建一個的IDE。 – Duck 2011-04-21 16:31:40

2

您參考Database.h中的代碼,因此您必須在庫或通過目標文件Database.o(或源文件Database.cpp)中提供實現。

0

而不是

g++ -std=c++0x main.cpp -o test 

嘗試像

g++ -std=c++0x main.cpp Database.cpp -o test 

這應該修復鏈接過程中缺失的引用。

0

您正在嘗試編譯沒有數據庫源文件的main.cpp。將數據庫對象文件包含在g ++命令中,這些函數將被解析。

我幾乎可以向你保證,這將成爲一個快速的痛苦。我建議使用make來管理編譯。

1

您還需要編譯Database.cpp,並將兩者連接在一起。

此:

g++ -std=c++0x main.cpp -o test 

嘗試編譯main.cpp一個完整的可執行文件。由於Database.cpp代碼是從來不碰,你會得到鏈接錯誤(你喊成是從來沒有定義的代碼)

而且這樣的:

g++ -std=c++0x main.cpp Database.cpp -o test 

編譯兩個文件到可執行

最後選項:

g++ -std=c++0x main.cpp Database.cpp -c 
g++ main.o Database.o -o test 

首先將兩個文件編譯成獨立的對象fiels(的.o),然後將它們鏈接在一起成一個單一的可執行文件。

您可能想了解C++中的編譯過程是如何工作的。