I am trying to wrap existing function.
below code is perfectly worked.
#include
int __real_main();
int __wrap_main()
{
printf(\
The answer proposed by PSCocik works great if you can split the function you want to override from the function that will call it. However if you want to keep the callee and the caller in the same source file the --wrap
option will not work.
Instead you can use __attribute__((weak))
before the implementation of the callee in order to let someone reimplement it without GCC yelling about multiple definitons.
For example suppose you want to mock the world
function in the following hello.c code unit. You can prepend the attribute in order to be able to override it.
#include "hello.h"
#include
__attribute__((weak))
void world(void)
{
printf("world from lib\n");
}
void hello(void)
{
printf("hello\n");
world();
}
And you can then override it in another unit file. Very useful for unit testing/mocking:
#include
#include "hello.h"
/* overrides */
void world(void)
{
printf("world from main.c"\n);
}
void main(void)
{
hello();
return 0;
}