Wrap malloc but only for some of input files (object and lib) Wrap malloc but only for some of input files (object and lib) unix unix

Wrap malloc but only for some of input files (object and lib)


Try linking in two steps.

First stage: ld -r -o libwrapped.a --wrap=malloc myobj1.o myobj2.o -lsomelib

Second stage: ld -o final -lwrapped -lsomeotherlib

The -r option makes the first file (wrapped) relocatable, often called partial linking. Basically you make a library of all the objects you want wrapped, then link that with the ones you don't want wrapped into the final object.


If you need to change the malloc for only some modules, or even part of modules, I would suggest to use a simple #define. This allows to restrict the use of the new malloc to some parts of the same module:

...#define malloc(x)  MyMalloc(x)...    //From here on will be used the new malloc MyMalloc#undef malloc...    //From here on will be used the standard malloc