Thursday, March 5, 2020

C: Autogen headers

It is known that I don't like writing header files and forward declarations. The keyword is writing, I like what you can do with header files, however I would also like to have an option, some times, to just autogen the headers. Also it could be nice to have a header file even in a single file program just to avoid forward declarations.

Lets thing about it... ok you need a C parser because C can be crazy some times. You can have macros and also you can have all kinds of whitespace in a function declaration. So you either write a program witch handles everything or you write a one-line bash thingy to handle only your style of code.

Lets do the second one (obviously). I write functions like this:

int send(cost char* text) {

So we grep all the lines which start with a character and end with a open bracket and then we replace the bracket with a semicolon:

grep '^\w.* {$' | sed 's/ {/;/'

Ok, lets put it in the Makefile:

%.h: %.c
    cat $< | grep '^\w.* {$$' | sed 's/ {/;/' > $@

What about the structs? Done, already handled.
What about typedefs? Nope... next post?

And a bonus effect is that if you include the header of the source file in its self you no longer need forward declarations.



done_