title: unresolved symbol __real_malloc while dynamically loading a library which is compiled with --wrap=malloc
body: <p>As mentioned in other SO answers I am using the wrapping mechanism of GNU ld to intercept calls to <code>malloc</code> on Linux (see <a href="https://stackoverflow.com/questions/3662856/how-to-reimplement-or-wrap-a-syscall-function-in-linux">here</a> for an example).
  The used linker flag is <code>-Wl,--wrap=malloc</code> and the respective <code>void __wrap_malloc(size_t)</code> is also defined.
  This works fine in a test application where all compilation unit are linked into the same binary.</p>
  
  <p>Now, I need to modify a dynamically linked library which is loaded into a main program via <code>dlopen()</code>.
  Linking the library succeeds, but loading it into the main program fails with <code>undefined symbol: __real_malloc</code>.</p>
  
  <p>Running <code>nm</code> on the library shows that <code>__wrap_malloc</code> is defined but <code>__real_malloc</code> is not.
  But, according to <code>man ld</code> and <a href="https://stackoverflow.com/a/12766024">this</a> SO answer, <code>malloc</code> should get replaced with <code>__wrap_malloc</code> and <code>__real_malloc</code> should point to <code>malloc</code> when using this technique.</p>
  
  <p>In the test application, I see that <code>__real_malloc</code> is undefined in the compiled object files but is resolved after getting linked into the executable.</p>
  
  <p>So, why is the symbol resolved in the test application but not in the dynamic library?
  In both cases a final link step is performed which should resolve this symbol.
  Or is it required to add another library during the link step of the dynamic library in order to get <code>__real_malloc</code> resolved?</p>
  
  <p>Just in case, it is not possible to modify the target application which loads the dynamic library via <code>dlopen</code>.</p>