views:

84

answers:

4

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!

+2  A: 

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
Carl Norum
+1  A: 

I just tried it with some C code I'm currently using - I linked in an object that contained a method not (yet) used anywhere else in the program. The code was included in the resultant executable, checked by running nm against the elf file and observing that the method T was indeed there, even with -O2 and -O3 used.

Ninefingers
+1  A: 

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.

osgx
+2  A: 

Yes, GCC will include all object files. With a very recent compiler (development version 4.5.0), you can use -flto (link-time optimization) to perform that.

FX