Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

GCC – Using –wrap flag on assert() function

I have a module, lets call it fut:

fut.h

int fut(int n);

fut.c

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

#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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading