5

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

但是,在我的系统上,链接选项 ( -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_REMOVEDELF 部分.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

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

4

1 回答 1

8

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

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

将选项应用于无对象 - 所以什么都不做。

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

应该管用

于 2013-04-17T04:46:14.803 回答