未定义对B::B和B::~B的引用

5

我不断收到来自g++编译器的抱怨,说以下代码存在问题。 经过仔细检查,我仍然无法理解为何它找不到embedMain.cpp中类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

// 更新 //

根据专家的评论,我找到了将embedMain.cpp与embed库链接的正确方法。

以下是详细步骤:

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

你两次发布了 embed.cpp,而且似乎把 embed.cppembedMain.cpp 搞混了。 - Kerrek SB
embedMain.cpp 是什么样子?你重复发布了 embed.cpp - Victor Parmar
感谢您指出这个问题,我已经更正了帖子。 - q0987
2个回答

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

真的,在长远的计划中,你需要一个构建系统来为你处理这个问题。 - Kos
2
@Kos,这个可能性太小了,我宁愿从那之前开始,也不会有两个源文件。 - mmmmmm

3
你还需要在编译/链接中包含embed.cpp文件。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接