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

Started by
5 comments, last by mark_braga 6 years, 7 months ago

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");
{
	pStruct->addVariable("Buffer*", "pBuffer");
	pStruct->addVariable("Texture*", "pTexture");
}
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

Advertisement

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

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.

Hm sorry but I need to ask - but why?

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.
 

 

 

Omae Wa Mou Shindeiru

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

This topic is closed to new replies.

Advertisement