Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compiling nonessential object files with GCC

Consider the following example

g++ a.o b.o c.o -o prog

If it is the case that c.o does not contribute any executable code to prog, nor are there any dependencies on c.o in any of the other files, will GCC yet include the contents of c.o in prog?

Said another way, aside from compilation time, what (if any) negative consequences can there be of compiling unnecessary files into an executable?

Thanks in advance; Cheers!

like image 274
Chris Tonkinson Avatar asked Feb 07 '10 03:02

Chris Tonkinson


2 Answers

There aren't any negative consequences except that your executable might be unnecessarily large. The linker can probably dead strip unused code for you, and that will shrink things back down. You can use some kind of object viewing tool (otool, objdump, nm, etc.) on the output executable to see if your program has extra symbols in it.

I'm using a Mac, so there will be some differences if you're using the standard set of gcc tools, but here's an example:

$ make
gcc -o app main.c file2.c
gcc -Wl,-dead_strip -o app_strip main.c file2.c
$ ls -l app*
-rwxr-xr-x  1 carl  staff  8744 Feb  6 20:05 app
-rwxr-xr-x  1 carl  staff  8704 Feb  6 20:05 app_strip

I think in the non-Apple gcc world, you would pass -Wl,--gc-sections instead of the -Wl,-dead_strip in my example. The size difference in the two executables you can see is due to the extra function being stripped:

$ nm app | cut -c 20- > app.txt
$ nm app_strip | cut -c 20- > app_strip.txt 
$ diff app.txt app_strip.txt 
8d7
< _function2
like image 103
Carl Norum Avatar answered Sep 20 '22 23:09

Carl Norum


llvm can eliminate dead code on linking step. It uses special linker llvm-ld.

Also, using -fwhole or -ipo (intel) will help to stripe dead symbols away.

like image 41
osgx Avatar answered Sep 19 '22 23:09

osgx