【问题标题】:linker option to ignore unused dependencies链接器选项忽略未使用的依赖项
【发布时间】:2023-03-08 13:35:01
【问题描述】:

我想从已编译的 C++ 二进制文件中删除所有未使用的符号。我看到了这个,它给出了使用 gcc 的概述,这是我正在使用的工具链:How to remove unused C/C++ symbols with GCC and ld?

但是,在我的系统上,链接选项 (-Wl,--gc-sections) 被拒绝:

$ gcc -fdata-sections -ffunction-sections a.c -o a.o -Wl,--gc-sections
ld: fatal: unrecognized option '--'
ld: fatal: use the -z help option for usage information
collect2: error: ld returned 1 exit status

我在 illumos 上运行,它是(相对)最近的 Solaris 分支,带有 GCC 4.7。有人知道这里使用的正确链接器选项是什么吗?


编辑:更仔细地搜索手册页出现“-zignore”:

 -z ignore | record

     Ignores, or records, dynamic dependencies that  are  not
     referenced   as  part  of  the  link-edit.  Ignores,  or
     records, unreferenced ELF sections from the  relocatable
     objects  that  are  read  as  part  of the link-edit. By
     default, -z record is in effect.

     If an ELF section is ignored, the section is  eliminated
     from  the  output  file  being  generated.  A section is
     ignored when three conditions are true.  The  eliminated
     section  must  contribute to an allocatable segment. The
     eliminated section must provide no  global  symbols.  No
     other  section  from  any object that contributes to the
     link-edit, must reference an eliminated section.

但是以下序列仍然将FUNCTION_SHOULD_BE_REMOVED 放入ELF 部分.text.FUNCTION

$ cat a.c
int main() {
    return 0;
}
$ cat b.c
int FUNCTION_SHOULD_BE_REMOVED() {
    return 0;
}
$ gcc -fdata-sections -ffunction-sections -c a.c -Wl,-zignore
$ gcc -fdata-sections -ffunction-sections -c b.c -Wl,-zignore
$ gcc -fdata-sections -ffunction-sections a.o b.o -Wl,-zignore
$ elfdump -s a.out                     # I removed a lot of output for brevity
Symbol Table Section:  .dynsym
[2]  0x08050e72 0x0000000a  FUNC GLOB  D    1 .text.FUNCTION FUNCTION_SHOULD_BE_REMOVED
Symbol Table Section:  .symtab
[71]  0x08050e72 0x0000000a  FUNC GLOB  D    0 .text.FUNCTION FUNCTION_SHOULD_BE_REMOVED

因为手册页说“没有全局符号”,所以我尝试将函数设置为“静态”,并且最终结果相同。

【问题讨论】:

  • ld 版本 2.23.52.0.1 (2013, CentOS 7.0) 不幸的是不支持-z ignore

标签: gcc linker solaris


【解决方案1】:

ld '-z ignore' 选项是位置性的,它适用于在命令行上出现在它之后的那些输入对象。你举的例子:

gcc a.o b.o -Wl,-zignore

将选项应用到没有对象——所以什么都不做。

gcc -Wl,-zignore a.o b.o

应该有效

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-13
    • 1970-01-01
    • 1970-01-01
    • 2011-10-31
    • 2011-04-04
    相关资源
    最近更新 更多