メモ:gccで不要な関数をリンクしない方法
普通はリンカはライブラリ(.a)になっている場合にはいらないファイル(.o)ごと消してくれる。これを関数単位で消してもらおう、という話。
-ffunction-sections -Wl,--gc-sections
らしい。ここ(radiumsoftware.com)より。
しかし、消えない。Oops!
使っていないfunc2()
が残ってしまう。
#include <stdio.h>
int func1(){ printf(“Hello, World!\n”); } int func2(){ printf(“Good-bye, World!\n”);}
int main(int argc, char **argv){ func1(); return 0; }
gcc -ffunction-sections -Wl,–gc-sections test.c
objdump -d a.out
:(略) 08048338 : 8048338: 55 push %ebp 8048339: 89 e5 mov %esp,%ebp 804833b: 83 ec 08 sub $0x8,%esp 804833e: c7 04 24 e4 83 04 08 movl $0x80483e4,(%esp,1) 8048345: e8 1e ff ff ff call 8048268 <_init+0x38> 804834a: c9 leave 804834b: c3 ret
0804834c : 804834c: 55 push %ebp 804834d: 89 e5 mov %esp,%ebp 804834f: 83 ec 08 sub $0x8,%esp 8048352: c7 04 24 f3 83 04 08 movl $0x80483f3,(%esp,1) 8048359: e8 0a ff ff ff call 8048268 <_init+0x38> 804835e: c9 leave 804835f: c3 ret :(略)
しかしながら、-ffunction-sections
は機能していて、以下のように関数毎にセクションに分かれてコードも正しく配置されている。
gcc -c -ffunction-sections test.c
objdump -d test.o
test.o: file format elf32-i386
Disassembly of section .text: Disassembly of section .text.func1:
00000000 : 0: 55 push %ebp 1: 89 e5 mov %esp,%ebp 3: 83 ec 08 sub $0x8,%esp 6: c7 04 24 00 00 00 00 movl $0x0,(%esp,1) d: e8 fc ff ff ff call e <func1+0xe> 12: c9 leave 13: c3 ret Disassembly of section .text.func2:
00000000 : 0: 55 push %ebp 1: 89 e5 mov %esp,%ebp 3: 83 ec 08 sub $0x8,%esp 6: c7 04 24 0f 00 00 00 movl $0xf,(%esp,1) d: e8 fc ff ff ff call e <func2+0xe> 12: c9 leave 13: c3 ret Disassembly of section .text.main:
00000000 : 0: 55 push %ebp 1: 89 e5 mov %esp,%ebp 3: 83 ec 08 sub $0x8,%esp 6: 83 e4 f0 and $0xfffffff0,%esp 9: b8 00 00 00 00 mov $0x0,%eax e: 29 c4 sub %eax,%esp 10: e8 fc ff ff ff call 11 <main+0x11> 15: c9 leave 16: c3 ret
してみると、リンカが悪いのかな?? binutilsのバージョン上げてみようかな。
(追記) 2004-02-03 13:26
-static
つけたら消えた。
gcc -static -ffunction-sections -Wl,–gc-sections test.c
objdump -d a.out | grep func
0804819d : 80481c1: e8 d7 ff ff ff call 804819d
そういう問題じゃなくて?
(追記) 2004-02-03 14:19
ld(1)に、次のように書いてあった。
--no-gc-sections
--gc-sections
Enable garbage collection of unused input sections. It is ignored
on targets that do not support this option. This option is not
compatible with -r, nor should it be used with dynamic linking.
The default behaviour (of not performing this garbage collection
can be restored by specifying --no-gc-sections on the command line.
ダイナミックリンクはダメだってさ。