Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing C++ to make some changes in the code

Tags:

c++

parsing

I would like to write a small tool that takes a C++ program (a single .cpp file), finds the "main" function and adds 2 function calls to it, one in the beginning and one in the end.

How can this be done? Can I use g++'s parsing mechanism (or any other parser)?

like image 974
user302099 Avatar asked Jun 17 '11 17:06

user302099


2 Answers

If you want to make it solid, use clang's libraries.

like image 187
Johannes Schaub - litb Avatar answered Sep 27 '22 15:09

Johannes Schaub - litb


As suggested by some commenters, let me put forward my idea as an answer:

So basically, the idea is:

... original .cpp file ...

#include <yourHeader>
namespace { 
  SpecialClass  specialClassInstance;
}

Where SpecialClass is something like:

class SpecialClass {
  public:
    SpecialClass() {
        firstFunction();
    }

    ~SpecialClass() {
        secondFunction();
    }
}

This way, you don't need to parse the C++ file. Since you are declaring a global, its constructor will run before main starts and its destructor will run after main returns.

The downside is that you don't get to know the relative order of when your global is constructed compared to others. So if you need to guarantee that firstFunction is called before any other constructor elsewhere in the entire program, you're out of luck.

like image 26
Lambdageek Avatar answered Sep 27 '22 15:09

Lambdageek