Skip to content

Mocking: objcopy override

Example: share/doc/aceunit/examples/hello_world_mocked_obj

  1. objcopy rewrites the compiled hello.o into mocked_hello.o, renaming symbols directly in the object file:
    • mainoriginal_main
    • putsmock_puts
  2. A mock_puts.c provides the replacement mock_puts(), recording calls into a buffer, plus assert_puts() to check what was recorded.
  3. The test calls original_main(), then assert_puts() to verify the expected output was “written”.
Terminal window
objcopy --redefine-sym main=original_main --redefine-sym puts=mock_puts hello.o mocked_hello.o
void test_hello(void) {
original_main();
assert_puts("Hello, world!\n");
}

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.