Skip to content

Instantly share code, notes, and snippets.

@mlabbe
Last active March 19, 2024 10:34
Show Gist options
  • Save mlabbe/a0b7b14be652085341162321a0a08530 to your computer and use it in GitHub Desktop.
Save mlabbe/a0b7b14be652085341162321a0a08530 to your computer and use it in GitHub Desktop.
Use clang linker --wrap to wrap a function in the same compilation unit
#!/bin/sh -x
CC=clang-9
rm -f *.o wrap nowrap
# build without wrapping
$CC -c wrap.c -o wrap.o
$CC -c wrap_b.c -o wrap_b.o
$CC wrap.o wrap_b.o -o nowrap
# build with wrapping, -DWRAP only affects wrap_b.c and is not
# integral to using --wrap
rm -f *.o
$CC -DWRAP -c wrap.c -o wrap.o
$CC -DWRAP -c wrap_b.c -o wrap_b.o
$CC -Wl,--wrap=moveme wrap.o wrap_b.o -o wrap
$ ./nowrap
moveme
$ ./wrap
wrap_moveme
moveme
void moveme(void);
int main(void) {
moveme();
return 0;
}
#include<stdio.h>
#ifdef WRAP
void __wrap_moveme(void) {
puts("wrap_moveme");
__real_moveme();
}
#endif
void moveme(void) {
puts("moveme");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment