I have a header-only library that's currently calling malloc
and free
This header is included in a lot of different static libraries, which are used to build differently configured programs.
I would like to be able to replace those calls with calls into another allocator, at link time -- based on whether that allocator library is included in the link step, without affecting other calls to malloc
and free
.
My idea is to have the library call customizable_malloc
and customizable_free
and have those symbols resolve to malloc
and free
"by default" -- then the allocator library can provide alternate definitions for customizable_malloc
and customizable_free
However, I messed around with weak/alias/weakref attributes and I can't seem to get anything to work. Is there a way to do this?
Note: I know I can create an extra layer of indirection: customizable_malloc
could be a weak alias to a function that calls malloc. But that adds a level of indirection that seems unnecessary.
Ideally, here's the steps I want the linker to take when it comes across a call to customizable_malloc:
- Check if a definition for customizable_malloc exists
- If it does, call it
- If it does not, behave as if the call was to regular malloc.
Clarifying note: In a single-target scenario, this could be done with #define
. The library could create macros customizable_malloc
and customizable_free
that default to malloc
and free
. However, this doesn't work in this case since things are being built into static libraries without knowledge of whether there's an override.