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

Dan*_*Dan 5 linker gcc solaris

我想从我编译的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
Run Code Online (Sandbox Code Playgroud)

我正在运行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.
Run Code Online (Sandbox Code Playgroud)

但是,以下序列仍然放入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
Run Code Online (Sandbox Code Playgroud)

因为手册页说"没有全局符号",所以我尝试使函数"静态"并且具有相同的最终结果.

小智 8

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

gcc a.o b.o -Wl,-zignore
Run Code Online (Sandbox Code Playgroud)

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

gcc -Wl,-zignore a.o b.o
Run Code Online (Sandbox Code Playgroud)

应该管用