我不斷收到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
你發佈了兩次'embed.cpp',你似乎很困惑'embed.cpp'和'embedMain.cpp'。 –
'embedMain.cpp'看起來像什麼?你加倍發佈'embed.cpp' –
謝謝你爲我指出這一點,我已經糾正了這個帖子。 – q0987