简体   繁体   中英

Using tcmalloc in a shared library

I have many executables that are linked with tcmalloc (.a). I usually do it at the executable level, so that any shared library loaded by the executable benefits from tcmalloc.

However, I have a scenario where I need to provide a .so library to an user.

Is it ok to use tcmalloc in that shared library?

What happens if the user's executable itself is not linked with tcmalloc?

Thanks.

Is it ok to use tcmalloc in that shared library?

It depends on a few things:

  • Whether your shared library is linked with tcmalloc in such a way that it exposes malloc and operator new as external symbols. Normally, it does.
  • Whether the user of your library links to your library or loads it at run-time with dlopen and what dlopen options are used.

What happens if the user's executable itself is not linked with tcmalloc?

One of the two things can happen:

  1. malloc is already a resolved symbol in user's application/process. In this case your .so uses that malloc . That happens when the user loads your .so with dlopen .
  2. malloc is not resolved yet, so that user's application/process uses malloc from tcmalloc from your .so . That happens when the user links against your .so in linker command line and your .so comes before -lc .

It may be most robust for your .so to not link tcmalloc at all. The user of the application can then decide which malloc implementation to use either by linking against tcmalloc or other allocator, or trying different allocators by pre-loading them at run-time using LD_PRELOAD .

You may like to learn how Unix linkers work to answer such questions yourself in the future.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM