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

kdt picture kdt · Oct 12, 2009 · Viewed 8.7k times · Source

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:

  • I'm using lots of C++ new etc, so just #defining malloc to tcmalloc won't work
  • Possibly I have to use malloc_hook myself, but I would have thought I could get tcmalloc to do it for me, since it clearly is doing it when linking dynamically

Answer

Clifford picture Clifford · Oct 12, 2009

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.