0

我正在开发一个链接到多个二进制文件的静态库。我的目标是在我的库被链接时减少它的内存占用。

我的库的用户需要我在库的 cpp 文件中创建的某些全局对象,然后导出具有这些变量的外部声明的头文件。

问题是,根据库的使用方式,其中一些全局变量可能根本无法使用。

以下代码在一定程度上显示了我的代码结构:

Foo.hpp:

class Foo
{
    static int      sFooListIndex = 0;
    static Foo *    sFooList[10] = { nullptr };

public:
    Foo()
    {
        if(sFooListIndex < 10)
        {
            sFooList[sFooListIndex++] = this;
        }
    }
}

Bar1.hpp:

#include "Foo.hpp"

class Bar1 : public Foo
{
public:
    Bar1() : Foo() { }
}

Bar2.hpp:

#include "Foo.hpp"

class Bar2 : public Foo
{
public:
    Bar2() : Foo() { }
}

全局.cpp:

#include "Bar1.hpp”
#include "Bar2.hpp"

static Bar1 bar1;
Foo & foo1 = bar1;

static Bar2 bar2;
Foo & foo2 = bar2;

导出.hpp:

#include "Foo.hpp"

extern Foo & foo1;
extern Foo & foo2;

这是我的问题:

  1. 如果包含我的库的项目只使用 foo1,那么 foo2 会从最终的二进制文件中删除吗?因此,Bar2 类的代码也会被删除吗?

  2. 如果没有,你知道我可以如何重组我的代码,以便在链接过程中去掉未使用的符号和未使用的代码吗?我能想到的唯一方法是将 Globals.cpp 和 Export.hpp 移动到包含我的库的项目中。还有其他方法吗?

  3. 我能想到的一种方法是将 Globals.hpp 和 Export.hpp 拆分为更小的文件,其中包含一组有意义的声明和定义。那会有帮助吗?

4

0 回答 0