How to simulate a function in C when its caller function is defined in the same file?

I'm trying to make fun of a function in C, mocking works great when the function and its caller function are defined in different files. But when both functions (the function itself and its caller) are defined in one file, the mocked function is not called.


Case 1:

//test.c

#include <stdio.h>

/*mocked function*/
int __wrap_func() {
   printf("Mock function !!!\n"); 
}

/*caller function*/
int myTest() {
  return func();
}

int main() {
    myTest();
    return 0;
}

//file.c
#include<stdio.h>

/*function need to be mocked*/
int func() {
  printf("Original function !!!\n");
    }

Case 2:

//test.c
#include <stdio.h>
extern int myTest();
/*mocked function*/
int __wrap_func() {
  printf("Mock function !!!\n");
}

int main() {
    myTest();
}
//file.c
#include<stdio.h>

/*function need to be mocked*/
int func() {
  printf("Original function !!!\n");
}

/*caller function*/
int myTest() {
  return func();
}

Code Compilation Command: gcc -Wl, - wrap = func test.c file.c

In Case 1 . Mock function !!!
In Case 2 . Original function !!!

In case 2, the mocking function is not called. I am looking for a solution in which I can make fun of a function, even the calling function and the called functions are in the same file.

+4
source share
3 answers

You can not.

From the linker documentation ,

-      . undefined __wrap_symbol. undefined __real_symbol . . __wrap_symbol. , __real_symbol. :

void *
__wrap_malloc (int c)
{
  printf ("malloc called with %ld\n", c);
  return __real_malloc (c);
}

--wrap malloc, malloc __wrap_malloc. __real_malloc __wrap_malloc malloc . , __real_malloc, --wrap .

...

, __real_malloc , __wrap_malloc; , , malloc.

+1

, , - undefined C.

( , __wrap_func func, .)

, .

+3

--wrap=symbol linker , undefined __wrap_symbol. func undefined, __wrap_func, . myTest, extern. myTest func, , undefidend , int func(). , func - . , , . MACRO function pointer, .

+1
source

All Articles