Skip to content

Mocking: Compile-time macro

Example: share/doc/aceunit/examples/hello_world_mocked_macro

The source under test is compiled twice: once normally, and once with macros that rename the identifiers before the compiler ever sees them:

Terminal window
cc -Dputs=mocked_puts -Dmain=original_main -c hello.c -o mocked_hello.o

Every occurrence of puts in hello.c is textually replaced with mocked_puts, and main with original_main, at preprocessing time. Link that object together with your mock_puts.c (defining mocked_puts) and your test (calling original_main()).

This is the most portable option — it relies on nothing but the C preprocessor, so it works with any compiler, including on toolchains without objcopy or GNU-style --wrap. The tradeoff: the file under test is compiled a second time with different flags, so build setup needs an extra rule for the “mocked” object.

See also: objcopy override and Link-time wrap for approaches that don’t require recompiling the source under test.