简体   繁体   中英

undefined reference to B::B & B::~B

I keep getting complaint from the g++ compiler that the following code has problems. After careful examination, I still cannot figure out why it cannot find the constructor and destructor of class B from embedMain.cpp.

Can someone give me a little hint?

Thank you

// 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 comments from experts here, I have found the right way to link the embedMain.cpp with the embed library.

Here is the detail 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

You need to compile embed.cpp and link it into your executable, like so:

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

您还必须在编译/链接中包含embed.cpp。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM