[svlug] simple C parser in C/C++/python

Michael Eager eager at eagercon.com
Tue Jun 7 11:20:22 PDT 2016

On 06/07/2016 08:22 AM, Ivan Sergio Borgonovo wrote:
> I've to generate some C code from some C code [sic].
> I've a C struct, some #define in some headers and I should generate some
> C code from them. The resulting C code will then be further compiled
> into another program.
> Currently I wrote a C++ program that simply include the #define and the
> struct, get compiled, the resulting C program get executed and produce
> the C code.
> That somehow is mostly OK since I can relay on a C compiler and it's as
> efficient as it needs to be, but I find it a bit messy.
> One option that came to mind was to use some parsing C library that
> digest the C source and output C source, making the program self
> sufficient and avoiding one compilation step.

You can use yacc/bison/flex to do parsing or other packages like ANTLR.
You may be able to find a grammar for the C language on-line, but it is
likely to be large and complex.  It's also likely designed to generate
a syntax tree for semantic processing, which I doubt is what you want.
(I'll also mention that yacc grammars are challenging to understand and
that creating a subset can be difficult.)

If you have a fairly restricted input domain, where you are just looking
for certain lines in a well structured format, you can use simpler parsing
tools, like awk or perhaps python.

The scheme you use now, by running a program using an include, sounds
like it is probably easier than both of these options.

Michael Eager	 eager at eagercon.com
1960 Park Blvd., Palo Alto, CA 94306  650-325-8077

More information about the svlug mailing list