c++linkermalloctcmalloc

tcmalloc: how can I get my malloc calls overridden when compiling statically?


When I use LD_PRELOAD=/usr/local/lib/libtcmalloc.so, all my calls to malloc become tcmalloc calls. However, when I link statically against libtcmalloc, I find that straight malloc is getting called unless I still use the LD_PRELOAD setting.

So how can I statically compile against tcmalloc in such a way that my mallocs hook into tcmalloc?

Notes:


Solution

  • Symbols are resolved on a first match basis. You need to make sure that libtcmalloc.a is searched before libc.a by the linker. I assume that you are not explicitly linking libc.a since you do not normally need to do so. The solution is to specify -nostdlibs, and then explicitly link all necessary libraries in the order you want them to be searched. Usually something like:

    -nostdlibs -llibtcmalloc -llibm -llibc -llibgcc
    

    Another solution which may be simpler, is to link the object file(s) needed to resolve tcmalloc rather than the static library, since object files take precedence over libraries in resolving symbols.