链接器选项以忽略未使用的依赖项

时间:2013-04-16 15:05:55

标签: gcc linker solaris

我想从已编译的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

因为手册页上写着“没有全局符号”,所以我尝试使函数“静态”并且具有相同的最终结果。

1 个答案:

答案 0 :(得分:8)

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

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

将选项应用于无对象 - 因此不执行任何操作。

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

应该工作