C++ 链接问题

标签 c++ linux g++ dynamic-linking

假设我有一个名为 libfoo.so 的共享库,它还依赖于另一个名为 libbar.so 的共享库。在 libfoo.so 中,它提供的唯一功能是一个存储两个整数并可以返回这两个整数加在一起的值的类。

libfoo.so:

// Foo.hpp

class Foo
{
  int x, y;
public:
  Foo(int x, int y);
  int add() const;
};

现在,在 libbar.so 中,有两个类:一个简单存储字符串的 Bar1 类和一个存储整数的 Bar2 类,该整数是通过创建 Foo 对象并使用 add() 函数生成一个新的整数。

// Bar1.hpp

class Bar1
{
  std::string str;
public:
  Bar1(const std::string& str);
  const std::string& getString() const;
};


// Bar2.hpp

#include "foo.hpp"

class Bar2
{
  int z;
public:
  Bar2(int x, int y);
  int getInt() const;
};

现在,我想编写一个使用 Bar1 的程序。我不关心 Bar2。我的非常简单的程序如下所示:

// Test.cpp

#include <iostream>

#include "Bar1.hpp"

using namespace std;

int main()
{
  Bar1 bar1("Hello");
  cout << bar1.getString() << endl;
}

我这样编译这个程序:

g++ -c test.cpp -o test.o
g++ -o test test.o -lbar

生成的错误是:

undefined reference to 'Foo::Foo(int, int)' 
undefined reference to 'Foo::add() const' 

这可以通过向链接器指定“-lfoo”来解决。但是,我现在正在链接一个我的二进制文件永远不会使用的库。

有没有办法在编译器理解我的二进制文件不关心解析这些符号的情况下清理它,因为我从不在我的程序中的任何地方使用 Bar2?

编辑:

添加类的实现。我认为这不重要。他们在这里:

// Foo.cpp

#include "Foo.hpp"

Foo::Foo(int new_x, int new_y)
{
  x = new_x;
  y = new_y;
}

int Foo::add() const
{
  return x + y;
}

这是 Bar1.cpp:

// Bar1.cpp

#include "Bar1.hpp"

Bar1::Bar1(const std::string& the_str)
{
  str = the_str;
}

const std::string& Bar1::getString() const
{
  return str;
}

这是 Bar2.cpp:

// Bar2.cpp

#include "Bar2.hpp"

Bar2::Bar2(int x, int y)
{
  Foo foo(x, y);
  z = foo.add();
}

int Bar2::getInt() const
{
  return z;
}

请注意,很明显,我像这样编写这些类纯粹是为了实验目的。我正在研究链接器以及开发人员如何链接到库并使用它们。

最佳答案

foo.cpp 和 bar.cpp 在哪里?你没有实现 foo 和 bar 类:

// foo.cpp
#include "Foo.hpp"

Foo::Foo(int X, int Y) : x(X), y(Y){}
int Foo::add()const{return x + y;}


// Bar1.cpp

#include "bar1.hpp"

Bar1::Bar1(const std::string& STR) : str(STR){}
const std::string& Bar1::getString() const{return str;}


// Bar2.cpp

#include "foo.hpp"

Bar2::Bar2(int X, int Y) : x(X), y(Y) {z = x + y;}  
int Bar2::getInt() const{ return z;}

关于C++ 链接问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39628032/

相关文章:

c++ - 如何以编程方式从工作线程获取父线程和兄弟线程的 CPU 利用率?

linux - 如何在 Red Hat Enterprise Linux 3 上构建 git?

linux - ImageMagick 中的文本语法是什么

c++ - 宏未在此范围内声明

c++ - 即使使用适当的方面,非有限 float 的反序列化也会失败

c++ - 有什么办法可以给数组的成员起不同的名字吗?

c# - 如何创建中间库?

python - 运行时错误与 Django on Amazon AWS EC2 Linux AMI 问题

c++ - 如何告诉 gcc 显示您使用的优化标志列表

c++ - 全局字符串在共享库中取消设置