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)?
As suggested by some commenters, let me put forward my idea as an answer:
So basically, the idea is:
Where
SpecialClassis something like:This way, you don’t need to parse the C++ file. Since you are declaring a global, its constructor will run before
mainstarts and its destructor will run aftermainreturns.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
firstFunctionis calledbefore any other constructor elsewhere in the entire program, you’re out of luck.