# C++ Is there a tool to write C++ code to a file

## Recommended Posts

I am working on a tool to auto-generate some C/C++ code by parsing a file. Is there a tool that provides an interface to write C/C++ code like this

Struct* pStruct = generator->beginStruct("Material");
{
}
generator->endStruct(pStruct);

/* Output file
struct Material
{
Buffer* pBuffer;
Texture* pTexture;
};
*/

Now I know its quite trivial to write a tool like this but I am curious to know whether a tool already exists. Seems just like a tool generating json/xml but for C++.

Note: I won't be doing any fancy stuff like templates or inheritance. Just pure C structs.

Thank you

##### Share on other sites

I would guess that you wouldnt find anything like that because it is redundant. XML and JSON are formated syntactical strict languages where inside a C file anything could be written that is formal correct in the first order. Thats why writing a XML or JSON parser is less time consuming than a C/C++ parser.

Maybe either you need to write it yourself or use something like an AST to get what you want. You could look at C#'s IL Code generator for an approach how they do it

##### Share on other sites

Code generators are typically used in the context of domain-specific languages, so anything you find would likely be tied to a specific language. It would probably be easier to write your own simple one from scratch rather than try and adapt another one to your needs.

Luckily there are some excellent references on DSLs out there.

##### Share on other sites

Hm sorry but I need to ask - but why?

Edited by RootKiller

##### Share on other sites

You can write an ad-hoc code generation tool with any text templating system.
I tend to use the string formatting features in Python: templates for different files and fragments can be placed in easy to write and freely indented multiline strings, placeholders support padding and numeric formatting if needed, input data can be produced in a dictionary and referenced by name, file handling is easy and convenient,  data structures and facilities to manage iteration, staged transformations, file fragments etc. (e.g. list and dictionary comprehensions) are very powerful and convenient.
You might be able to dispense with input files and place lists and dictionaries of source data in the code generation script. Another possible simplification is receiving a fixed set of output file names (e.g. a pair of .cpp and .h files) as command line parameters.

##### Share on other sites

I ended up writing my own. Use clang format to format the ugly generated code too  Makes my life a lot easier

## Create an account

Register a new account

1. 1
2. 2
Rutin
25
3. 3
4. 4
JoeJ
18
5. 5
gaxio
11

• 14
• 22
• 11
• 11
• 9
• ### Forum Statistics

• Total Topics
631765
• Total Posts
3002213
×