Replacing symbol from object file at compile time. For example swapping out main
- by Anthony Sottile
Here's the use case:
I have a .cpp file which has functions implemented in it. For sake of example say it has the following:
[main.cpp]
#include <iostream>
int foo(int);
int foo(int a) {
return a * a;
}
int main() {
for (int i = 0; i < 5; i += 1) {
std::cout << foo(i) << std::endl;
}
return 0;
}
I want to perform some amount of automated testing on the function foo in this file but would need to replace out the main() function to do my testing. Preferably I'd like to have a separate file like this that I could link in over top of that one:
[mymain.cpp]
#include <iostream>
#include <cassert>
extern int foo(int);
int main() {
assert(foo(1) == 1);
assert(foo(2) == 4);
assert(foo(0) == 0);
assert(foo(-2) == 4);
return 0;
}
I'd like (if at all possible) to avoid changing the original .cpp file in order to do this -- though this would be my approach if this is not possible:
do a replace for "(\s)main\s*\(" == "\1__oldmain\("
compile as usual.
The environment I am targeting is a linux environment with g++.