Issue
I have a module, lets call it fut
:
fut.h
int fut(int n);
fut.c
#include <assert.h>
int fut(int n)
{
if (n > 0)
{
assert(0);
}
return n;
}
I want to intercept the call of assert with --wrap
linker flag, but the linking fails with the message undefined reference to 'assert'
.
Here is the main function:
#include "fut.h"
#include <stdio.h>
static int useRealAssert = 1;
static int assertCalled;
void __real_assert(int expression);
void __wrap_assert(int expression)
{
if (1 == useRealAssert)
{
__real_assert(expression);
}
else
{
assertCalled = 1;
}
}
int main()
{
useRealAssert = 0;
printf("Calling fut...\n");
fut(1);
printf("assertCalled = %d\n", assertCalled);
}
and here is the build command:
gcc.exe -Wl,--wrap=assert -o my_program main.c fut.c
Any ideas why this doesn't work for assert
function? I am doing the same for malloc
and some other functions, and it works as I expect.
Solution
why this doesn't work for assert function?
Because it's a macro, not a function.
On glibc https://sourceware.org/git/?p=glibc.git;a=blob;f=assert/assert.h;hb=HEAD __assert_fail
function is called when assertion fails. On newlib https://github.com/eblot/newlib/blob/master/newlib/libc/include/assert.h it's __assert_func
. Depending on the standard C library implementation you are working it can be a different function, but it's easy to check it - just in your IDE jump to definition of assert and inspect the macro definition.
Answered By - KamilCuk Answer Checked By - Gilberto Lyons (WPSolving Admin)