Replacing symbol from object file at compile time. For example swapping out main

Posted by Anthony Sottile on Stack Overflow See other posts from Stack Overflow or by Anthony Sottile
Published on 2012-10-15T22:59:07Z Indexed on 2012/10/15 23:00 UTC
Read the original article Hit count: 207

Filed under:
|

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:

  1. do a replace for "(\s)main\s*\(" ==> "\1__oldmain\("
  2. compile as usual.

The environment I am targeting is a linux environment with g++.

© Stack Overflow or respective owner

Related posts about c++

Related posts about g++