2011-11-30 50 views
4

我不斷收到g ++編譯器的投訴,下面的代碼有問題。 經過仔細檢查,我仍然無法弄清楚爲什麼它無法從embedMain.cpp中找到B類的構造函數和析構函數。未定義的引用B :: B&B ::〜B

有人可以給我一點提示嗎?

謝謝

// embedMain.cpp 
#include "embed.h" 

int main(void) 
{ 
    B b("hello world"); 
    return 0; 
} 

// embed.h 
#ifndef EMBED_H 
#define EMBED_H 
#include <string> 

class B 
{ 
public: 
    B(const std::string& _name); 
    ~B(); 
private: 
    std::string name; 
}; 
#endif 

// embed.cpp 

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

B::B(const std::string& _name) : name(_name) {} 

B::~B() { 
    std::cout << "This is B::~B()" << std::endl; 
} 

~/Documents/C++ $ g++ --version 
g++ (Ubuntu/Linaro 4.5.2-8ubuntu4) 4.5.2 

~/Documents/C++ $ g++ -o embedMain embedMain.cpp 
/tmp/ccdqT9tn.o: In function `main': 
embedMain.cpp:(.text+0x42): undefined reference to `B::B(std::basic_string<char, std::char_traits<char>, std::allocator<char> > const&)' 
embedMain.cpp:(.text+0x6b): undefined reference to `B::~B()' 
embedMain.cpp:(.text+0x93): undefined reference to `B::~B()' 
collect2: ld returned 1 exit status 

// Updated //

根據這裏專家的評論,我找到了將embedMain.cpp與嵌入庫鏈接的正確方法。

下面是詳細的步驟:

[email protected]:~/Documents/C++$ tree 
. 
├── embed.cpp 
├── embed.h 
├── embedMain.cpp 

[email protected]:~/Documents/C++$ g++ -Wall -c embed.cpp 
[email protected]:~/Documents/C++$ ar -cvq libembed.a embed.o 
[email protected]:~/Documents/C++$ g++ -o embedMain embedMain.cpp -L/home/user/Documents/C++ -lembed 
[email protected]:~/Documents/C++$ tree 
. 
├── embed.cpp 
├── embed.h 
├── embedMain 
├── embedMain.cpp 
├── embed.o 
├── libembed.a 
+0

你發佈了兩次'embed.cpp',你似乎很困惑'embed.cpp'和'embedMain.cpp'。 –

+0

'embedMain.cpp'看起來像什麼?你加倍發佈'embed.cpp' –

+0

謝謝你爲我指出這一點,我已經糾正了這個帖子。 – q0987

回答

11

您需要編譯embed.cpp並將其鏈接到你的可執行文件,例如:

g++ -o embedMain embedMain.cpp embed.cpp 

這條命令編譯的文件和鏈接的一切。要分開這三個步驟:

g++ -c embed.cpp 
g++ -c embedMain.cpp 
g++ -o embedMain embedMain.o embed.o 
+0

確實如此,在長遠的眼光中,你需要一個能夠爲你照顧它的構建系統。 – Kos

+2

@Kos即使在漫長的拍攝過程中 - 我會先從那開始,然後纔有2個源文件 – Mark

3

您還必須在您的編譯/鏈接中包含embed.cpp。

相關問題