Undefined link to B :: B & B :: ~ B

I continue to complain from the g ++ compiler that there are problems in the following code. After a thorough study, I still cannot understand why he cannot find the constructor and destructor of class B from embedMain.cpp.

Can someone give me a little hint?

thanks

// 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 //

Based on expert comments here, I found the right way to link embedMain.cpp with the built-in library.

Here is the detailed step:

 user@ubuntu :~/Documents/C++$ tree . β”œβ”€β”€ embed.cpp β”œβ”€β”€ embed.h β”œβ”€β”€ embedMain.cpp user@ubuntu :~/Documents/C++$ g++ -Wall -c embed.cpp user@ubuntu :~/Documents/C++$ ar -cvq libembed.a embed.o user@ubuntu :~/Documents/C++$ g++ -o embedMain embedMain.cpp -L/home/user/Documents/C++ -lembed user@ubuntu :~/Documents/C++$ tree . β”œβ”€β”€ embed.cpp β”œβ”€β”€ embed.h β”œβ”€β”€ embedMain β”œβ”€β”€ embedMain.cpp β”œβ”€β”€ embed.o β”œβ”€β”€ libembed.a 
+4
source share
2 answers

You need to compile embed.cpp and link it to your executable, for example:

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

This compiles both files and links everything. To separate the three steps:

 g++ -c embed.cpp g++ -c embedMain.cpp g++ -o embedMain embedMain.o embed.o 
+11
source

You should also include embed.cpp in your compiler / link.

+3
source

Source: https://habr.com/ru/post/1383907/


All Articles