【问题标题】:gcc: Strip unused functionsgcc:剥离未使用的功能
【发布时间】:2017-04-12 21:53:42
【问题描述】:

我注意到,有时即使我不使用 iostream 和相关的 I/O 库,我的 Mingw 生成的二进制文件仍然大得不合理。

例如,我写了一个代码只使用vectorcstdio,并用-O2 -flto编译它,我的程序可以达到2MB!我运行nm main.exe > e.txt 并震惊地看到其中所有iostream 相关函数。

经过一番谷歌搜索,我学会了使用-ffunction-sections -Wl,-gc-sections,这将程序大小从 2MB 减少到 ~300KB(如果使用-s,则为 100+KB)。太棒了!

为了进一步测试-ffunction-sections -Wl,-gc-sections的效果,这里再写一段代码:

#include <cstdio>
#include <vector>
#include <tuple>
#include <algorithm>
#include <chrono>
#include <windows.h>

#undef min

struct Point {
    int x, y;
};

constexpr int length = 5;
constexpr int half_length() {
    return length & 1 ? length : length - 1;
}

template<class F>
int func_template(F&& f) {
#ifdef _MSC_VER
    puts(__FUNCSIG__);
#else
    puts(__PRETTY_FUNCTION__);
#endif
    printf("\n");
    return f();
}

struct fake_func {
    int operator()() const { return 59; };
};

template<class F, class... Args>
int pass_args(F&& f, Args&&... args) {
#ifdef _MSC_VER
    puts(__FUNCSIG__);
#else
    puts(__PRETTY_FUNCTION__);
#endif
    printf("\n");
    return f(std::forward<Args>(args)...);
}

template<class T>
T min(T x) {
    return x;
}

template<class T, class... Args>
T min(T x, Args... args) {
    T y = min(args...);
    return x < y ? x : y;
}

void type_verifier(int x) {
    printf("%dd ", x);
}

void type_verifier(char x) {
    printf("'%c' ", x);
}

void type_verifier(double x) {
    printf("%lff ", x);
}

template<class T>
void type_verifier(T x) {
    printf("unknown ");
}

template<class T, class... Args>
void type_verifier(T x, Args... args) {
    type_verifier(x);
    type_verifier(args...);
}

int bufLen;
char buf[100];

template<class... Args>
inline int send(Args... args) {
    bufLen = sprintf(buf, std::forward<Args>(args)...);
    return bufLen;
}

namespace std {

inline namespace v1 {
    void func() {
        printf("I am v1\n");
    }
}

namespace v2 {
    void func() {
        printf("I am v2\n");
    }
}

}

int main() {
    std::vector<int> v {1, 2, 3, 4, 5};
    for (auto &i : v) printf("%d ", i);
    printf("\n");

    Point p {1, 2};
    printf("%d %d\n", p.x, p.y);

    auto t = std::make_tuple("Hello World", 12);
    printf("%s %d\n", std::get<0>(t), std::get<1>(t));
    int a, b;
    auto f = []() { return std::make_tuple(1, 2); };
    std::tie(a, b) = f();
    printf("%d %d\n", a, b);

    //int test_constexpr[half_length() + 4];

    int ft = func_template([]{ return 42; });
    printf("func_template: %d\n", ft);
    ft = func_template(fake_func {});
    printf("func_template: %d\n", ft);
    ft = pass_args([](int x, int y) { return x + y; }, 152, 58);
    printf("pass_args: %d\n", ft);
    ft = pass_args([](int n, const char *m) {
        for (int i = 0; i < n; i++) printf("%c ", m[i]);
        printf("\n");
        return 0;
    }, 5, "Hello");

    printf("min: %d\n", min(3, 4, 2, 1, 5));
    type_verifier(12, 'A', 0.5, "Hello");
    printf("\n");

/*  send("Hello World");
    send("%d", 1);
    send("%d", "1234");
    sprintf(buf, "%d", "123");*/

    std::func();
    std::v1::func();
    std::v2::func();

    std::rotate(v.begin(), v.begin() + 2, v.end());
    for (auto &i : v) printf("%d ", i);
    printf("\n");

    auto start = std::chrono::steady_clock::now();

    std::vector<int> x {2, 4, 2, 0, 5, 10, 7, 3, 7, 1}; 
    printf("insertion sort: ");
    for (auto &i: x) printf("%d ", i);
    printf("\n");
    // insertion sort
    for (auto i = x.begin(); i != x.end(); ++i) {
        std::rotate(std::upper_bound(x.begin(), i, *i), i, i+1);
        for (auto &j: x) printf("%d ", j);
        printf("\n");
    }

    std::vector<int> heap {7, 5, 3, 4, 2};
    std::make_heap(heap.begin(), heap.end());
    std::pop_heap(heap.begin(), heap.end());
    printf("Pop heap (%d)\n", heap.back());
    heap.pop_back();
    heap.push_back(1);
    std::push_heap(heap.begin(), heap.end());
    std::sort_heap(heap.begin(), heap.end());
    for (auto &i: heap) printf("%d ", i);
    printf("\n");

    auto end = std::chrono::steady_clock::now();
    auto diff = end - start;
    printf("time: %I64d ms\n",
        std::chrono::duration_cast<std::chrono::milliseconds>(diff).count());

    {
        auto u = v;
        std::move_backward(u.begin(), u.begin() + u.size() - 1, u.begin() + u.size());
        for (auto &i : u) printf("%d ", i);
        printf("\n");
    }

    {
        auto u = v;
        std::move(u.begin() + 1, u.begin() + u.size(), u.begin());
        for (auto &i : u) printf("%d ", i);
        printf("\n");
    }

    start = std::chrono::steady_clock::now();
    Sleep(2000);
    end = std::chrono::steady_clock::now();
    diff = end - start;
    printf("time: %I64d ms\n",
        std::chrono::duration_cast<std::chrono::milliseconds>(diff).count());

    std::chrono::steady_clock::time_point before;
    before = std::chrono::steady_clock::now();
    Sleep(2000);
    auto after = std::chrono::steady_clock::now();
    printf("%f seconds\n", std::chrono::duration<double>(after - before).count());

    return 0;
}

令我失望的是,最终程序再次 > 2MB。

有趣的是,即使我没有使用/O2 或任何其他标志,cl.exe main.cpp 也始终如一地删除所有iostream 相关功能,cl.exe (对于上面的代码,cl.exe 产生 100+KB 的二进制文件)。

我是否错过了任何其他有用的 gcc 标志?

规格:

  • Mingw-w64 gcc 6.1.0
  • Mingw-w64 gcc 6.2.0
  • Visual Studio 2017 RC
  • 所有二进制文件都是静态链接的

与 Linux 比较

我比较了 gcc 4.9.2 (Linux) 和 gcc 4.9.3 (mingw-w64) 为上述代码生成的二进制文件(windows.hSleep 被删除)。

编译标志

g++ -o c++11 c++11.cpp -std=c++11 -static-libgcc -static-libstdc++ -ffunction-sections -Wl,-gc-sections -O2

Linux gcc 确实成功地剥离了 iostream 并在不需要 -flto 的情况下运行,而 Mingw-w64 gcc 无法正常执行。

Windows 仅支持 PE 格式,而 Linux 支持 ELF 格式,允许 Linux 使用 Gold 链接器。也许这就是解释?

更新

我最终在 https://sourceforge.net/p/mingw-w64/bugs/578/ 提交了一个错误。让我们希望它得到一些关注!

【问题讨论】:

  • 尝试了一切:-Os(减少 2KB)、-fwhole-program(无变化)、-fomit-frame-pointer(无变化)。 -why_live 不可用。
  • length &amp; 1 ? length : length - 1可以改成length + (length &amp; 1) - 1
  • 对我来说 -fwhole-program 做到了,使用来自 MSYS2 的 gcc 8.2.0。
  • 查看错误报告sourceware.org/bugzilla/show_bug.cgi?id=11539,其中包含一个正在进行中的补丁(该补丁已经两年没有更新了......)

标签: c++ visual-studio gcc visual-c++ iostream


【解决方案1】:

尝试通过-Wl,--strip-all 从静态 libstdc++ 中剥离调试和符号信息。这将我的可执行文件在 Cygwin (13x) 上从 9M 减少到 670K,在 Ubuntu (80x) 上从 6M 减少到 80K。

【讨论】:

  • -Wl,--strip-all 与我上面提到的-s 相同。剥离调试信息和符号表不会剥离未使用的 iostream 相关函数,这是 MSVC 无需告知的事情(不需要特殊标志)!
  • 好的,我明白了。仅供参考,带有-std=c++11 -O2 -ffunction-sections -Wl,-gc-sections -static-libstdc++ -s 的 4.8.2 x86_64-w64-mingw32-g++ (Ubuntu 14.04) 会生成 100K 的可执行文件,因此大小问题可能特定于特定的工具链版本(因此更难远程调查)。您是否尝试过分析链接器映射 (-Wl,--print-map)?
  • 由于我使用的是最新的MSVC,为了公平起见,我改成了gcc 6.2.0。 -Wl,-print-gc-sections 表明 gcc 确实剥离了一些 iostreamlocale 函数,但 -Wl,--print-map 表明仍有剩余。 MSVC:150KB,gcc:738KB。见pastebin.com/raw/4uGCm7Yy
  • 我认为您附加了 gc.txt 而不是 map.txt(转储包含 -print-gc-sections 的输出)。 “gcc: 738KB” - 我很困惑,最初你说它超过了 2M...
  • FWIW 在 PE/COFF 目标(即 MinGW/Cygwin)上对 --gc-sections 的实验性支持在 min-2015 中只有 landed in Bintools 2.25,因此它可能不是最佳的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-08-22
  • 2011-08-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-26
相关资源
最近更新 更多