Mocking: objcopy override
Example: share/doc/aceunit/examples/hello_world_mocked_obj
How it works
Section titled “How it works”objcopyrewrites the compiledhello.ointomocked_hello.o, renaming symbols directly in the object file:main→original_mainputs→mock_puts
- A
mock_puts.cprovides the replacementmock_puts(), recording calls into a buffer, plusassert_puts()to check what was recorded. - The test calls
original_main(), thenassert_puts()to verify the expected output was “written”.
objcopy --redefine-sym main=original_main --redefine-sym puts=mock_puts hello.o mocked_hello.ovoid test_hello(void) { original_main(); assert_puts("Hello, world!\n");}When to use this
Section titled “When to use this”Works on any GNU/Clang toolchain with objcopy (or llvm-objcopy on Darwin). No special linker flags needed at link time — the renaming happens once, up front, on the object file itself.
See also: Link-time wrap for an approach that defers the renaming to the linker instead.