Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Weak alias to mock

Tags:

c

I'm trying to mock a fn say foo using

#ifdef UT_TEST
    void foo(void)  __attribute__ ((weak, alias ("foo_impl")));
#else
    void foo(void);
#endif

However, is there a way to do this @ runtime instead of compile time? I cannot use C++, for historical reasons.

like image 446
kgunjikar Avatar asked Nov 25 '25 17:11

kgunjikar


1 Answers

In the past I've mostly seen this problem solved at the build system level instead, which I feel is a cleaner solution. Doing it this way allows to avoid most ifdefs and instead work with full files. In make, it might look something like this:

OBJS += file1.o file2.o
ifeq ($(UNIT_TEST),y)
OBJS += dummy_implementation.o
else
OBJS += real_implementation.o
endif

myprog: $(OBJS)

or in more classic make idiom:

OBJS-y += file1.o file2.o
OBJS-$(UNIT_TEST) += dummy_implementation.o
OBJS-$(REAL_BUILD) += real_implementation.o
OBJS = $(OBJS-y)

myprog: $(OBJS)

dummy_implementation.c and real_implementation.c would share a header file in this case.

like image 82
jforberg Avatar answered Nov 27 '25 07:11

jforberg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!