user2941479
user2941479

Reputation:

GCC's linker --wrap will not wrap over static library function

I am trying to mock C functions using CMocka and GCC's --wrap linker option. So far this technique has worked well for mocking stdlib functions such as fgets, popen, pclose, etc.

However now I am trying to mock functions that are in a static library and this does not work as well. In fact the static library function is always called, even if I try to mock it using --wrap. I have managed to reproduce this in a foobar project.

Here is the source code of my very simple static lib:

hello.h

#ifndef HELLO_H
#define HELLO_H

void hello();
void world();

#endif /* HELLO_H */

hello.c

#include "hello.h"
#include <stdio.h>

void world()
{
    printf("world from lib\n");
}

void hello()
{
    printf("hello\n");
    world();
}

And here is the source code of my test program:

tests.c

#include <stdarg.h>
#include <stddef.h>
#include <setjmp.h>

#include <stdio.h>

#include "cmocka.h"
#include "hello.h"


void __wrap_world(void)
{
    puts(mock_ptr_type(char*));
}

void test_hello(void **state)
{
    (void) state; /* unused */

    assert_int_equal(7, 1 + 2 * 3);

    will_return(__wrap_world, "world from tests\n");
    hello();
}

const struct CMUnitTest mytests[] = {
    cmocka_unit_test(test_hello),
};

int main(void)
{
    return cmocka_run_group_tests(mytests, NULL, NULL);
}

Finally, the linker line is as follows (I am using CMake so that's why it looks this weird), splitted on multiple lines for your eyes:

/usr/bin/cc \
  -Wall -Wextra -Werror -std=c99 \
  CMakeFiles/tests.dir/tests.c.o \
  -o tests -Wl,-rpath,/home/microjoe/cmake-fail/cmocka/build/src \
  -rdynamic -lgcov /home/microjoe/cmake-fail/cmocka/build/src/libcmocka.so \
  -Wl,--wrap,world \
  -fprofile-arcs -ftest-coverage \
  ../lib/libhello.a

And of course the tests output that shows that the wrap function was not called as expected:

[==========] Running 1 test(s).
[ RUN      ] test_hello
hello
world from lib
[  ERROR   ] --- __wrap_world() has remaining non-returned values.
/home/romain/cmake-fail/hello/tests/tests.c:23: note: remaining item was declared here

[  FAILED  ] test_hello
[==========] 1 test(s) run.
[  PASSED  ] 0 test(s).
[  FAILED  ] 1 test(s), listed below:
[  FAILED  ] test_hello

 1 FAILED TEST(S)

Upvotes: 1

Views: 4302

Answers (0)

Related Questions