Search code examples
gccldlinker-scripts

Why does ld's KEEP() does not keep my symbols?


Normally, by using KEEP(), ld keeps the symbols in the section even if symbols are not referenced. However, this is not my experience. I cannot create an ld linkerscript that retains symbols if they are not referenced.

Are there some preconditions for this to work?


Solution

  • KEEP does keep my symbols, but the presented archives were stripped beforehand of all the object files that were deemed to be unnecessary. To prevent that, the option --whole-archive must be used in the link command.

    From the man page of ld:

       --whole-archive
           For each archive mentioned on the command line after the
           --whole-archive option, include every object file in the archive in
           the link, rather than searching the archive for the required object
           files.  This is normally used to turn an archive file into a shared
           library, forcing every object to be included in the resulting
           shared library.  This option may be used more than once.
    
           Two notes when using this option from gcc: First, gcc doesn't know
           about this option, so you have to use -Wl,-whole-archive.  Second,
           don't forget to use -Wl,-no-whole-archive after your list of
           archives, because gcc will add its own list of archives to your
           link and you may not want this flag to affect those as well.