I want to mock functions of the c lib such as malloc
without altering too much the original source file (the one that uses malloc).
I tried including a header file "mock.h" like
#ifndef MOCK_H_
# define MOCK_H_
# ifdef MOCK_MODE
# include <sys/types.h>
extern void *my_mock_malloc(size_t n);
void *malloc(size_t n) __attribute__((weak, alias ("my_mock_malloc")));
# endif /* MOCK_MODE */
#endif /* !MOCK_H_ */
but it gives me an error
in file included from ...:
/usr/include/stdlib.h:466:14: error: ‘malloc’ aliased to undefined symbol ‘my_mock_malloc’
extern void *malloc (size_t __size) __THROW __attribute_malloc__ __wur;
GCC alias to function outside of translation unit -AKA- is this even the right tool for the job? gives a partial solution: using the linker I create an alias on a symbol. I can now compile with -Xlinker --defsym "malloc"="my_mock_malloc"
. The problem is that all my .o
files are linked using this option and thus the unit testing framework I use (check) is affected by the mocking (and thus it receives is SIGSEGV when I make my mock function return NULL
).
Is there a way to perform such symbol aliasing locally, so I can make my tesing framework use the real malloc? Os is there a better solution than this one?
Aucun commentaire:
Enregistrer un commentaire