Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically parse and edit C++ Source Files

Tags:

c++

parsing

I want to programmatically parse and edit C++ source files. I need to change/add code in certain sections of code (i.e. in functions, class blocks, etc). I would also (preferably) be able to get comments as well.

Part of what I want to do can be explained by the following piece of code:

CPlusPlusSourceParser cp = new CPlusPlusSourceParser(“x.cpp”);  // Create C++ Source Parser Object
CPlusPlusSourceFunction[] funcs = cp.getFunctions();  // Get all the functions

for (int i = 0; i &lt funcs.length; i++) {  // Loop through all functions
    funcs[i].append(/* … code I want to append …*/);  // Append some code to function 
}
cp.save(); // Save new source
cp.close(); // Close file

How can I do that?

I’d like to be able to do this preferably in Java, C++, Perl, Python or C#. However, I am open to other language API’s.

like image 636
Kryten Avatar asked Jul 20 '26 03:07

Kryten


2 Answers

This is similar to AST from C code

If your comfortable with Java antlr can easily parser your code into an abstract syntax tree, and then apply transformation to that tree. A default AST transform is to simply print out the original source.

like image 138
brianegge Avatar answered Jul 22 '26 20:07

brianegge


You can use any parser generator tool to generate a c++ parser for you, but first you have to get the CFG (context free grammar) for C++ , check Antlr

Edit:

Also Antlr supports a lot of target languages

like image 42
Ahmed Avatar answered Jul 22 '26 20:07

Ahmed



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!