Guest User

Untitled

a guest
Aug 11th, 2018
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.83 KB | None | 0 0
  1. Wrapping C functions with GNU linker
  2. //number.cpp
  3. int giveMeANumber() {
  4. return rand() % 6 + 1;
  5. }
  6.  
  7. //test.cpp
  8. extern "C" int __wrap_rand(void) {
  9. return 4;
  10. }
  11.  
  12. void unitTest() {
  13. assert giveMeANumber() == 5;
  14. }
  15.  
  16. $ g++ test.cpp -o test number.o -Xlinker --wrap=rand
  17.  
  18. //number.cpp
  19. int foo() {
  20. //some complex calculations I would like to mock
  21. }
  22. int giveMeANumber() {
  23. return foo() % 6 + 1;
  24. }
  25.  
  26. //test.cpp
  27. extern "C" int __wrap_foo(void) {
  28. return 4;
  29. }
  30.  
  31. $ g++ test.cpp -o test number.o -Xlinker --wrap=foo
  32.  
  33. $ cat x.cc
  34. #include <iostream>
  35. using namespace std;
  36.  
  37. int giveMeANumber();
  38.  
  39. int main() {
  40. cerr << giveMeANumber() << endl;
  41. return 0;
  42. }
  43.  
  44. $ cat y.cc
  45. int giveMeANumber() {
  46. return 0;
  47. }
  48.  
  49. extern "C" int __wrap__Z13giveMeANumberv() {
  50. return 10;
  51. }
  52.  
  53. $ g++ -c x.cc y.cc && g++ x.o y.o -Wl,--wrap=_Z13giveMeANumberv && ./a.out
  54. 10
Add Comment
Please, Sign In to add comment