Search code examples
gccld

Discard unused functions in GCC


I need some help for compiling with GCC under MinGW.

Say I have two files:

  • File a.c contains two functions, a1 and a2
  • File b.c contains two functions, b1 and b2.

Then I link the two objects into a shared library. The command used are like:

gcc -c a.c
gcc -c b.c
gcc -shared -Wl, --version-script v.ver -Wl, -Map=out.map -Wl, --strip-all -o mydll.dll a.o b.o

File v.ver looks like:

mylib {
   global: a1;
           a2;
   local: *;
}

which is used to control which functions to be exported.

By checking the mapfile I can see that the two functions in b.c are also included into the .text section of the DLL file.

Because this DLL file only exports a1 and a2, and b1 and b2 are only defined in b.c, but never used anywhere. Is there an option I could add in GCC or ld so that b1 and b2 are not built into the DLL file so that I can save some space in the DLL file?


Solution

  • Yes, this is possible. To do this, add the following two flags when compiling your C source code to objects:

     -ffunction-sections -fdata-sections
    

    This will generate bigger object files, but will add a lot of information for the linker. When calling the linker add the following flag:

    --gc-sections
    

    The linker will now throw away all functions and sections that are not used. Note that this might incur a performance penalty:

    Only use these options when there are significant benefits from doing so. When you specify these options, the assembler and linker create larger object and executable files and are also slower. These options affect code generation. They prevent optimizations by the compiler and assembler using relative locations inside a translation unit since the locations are unknown until link time. An example of such an optimization is relaxing calls to short call instructions. (man gcc)

    See also this question: Query on -ffunction-section & -fdata-sections options of gcc for more information.