Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating code at compile-time using scripts

Tags:

c++

c

gcc

I would ideally like to be able to add (very repetitive) C/C++ code to my actual code, but at compile time, code which would come from say, the stdout of a python script, the same way one does with macros.

For example, let's say I want to have functions that depend on the public attributes of a given class, being able to just write the following in my C++ code would be a blessing:

generate_boring_functions(FooBarClass,"FooBarClass.cpp")

Is that feasible using conventional means? Or must I hack with Makefiles and temporary source files?

Thanks.

like image 674
Manux Avatar asked Jun 17 '10 17:06

Manux


2 Answers

You do most likely need to tweak the Makefile a bit. It would be easy to write a (Python) script that reads each of your source files as an additional preprocessing step, replacing instances of generate_boring_functions (or any other script-macro) with the correct code, potentially just by invoking generate_boring_functions.py with the right arguments, and bypassing the need for temporary files by sending the source to the compiler over standard input.

Damn, now I want to make something like this.

Edit: A rule like this, stuck in a makefile, could be used to handle the extra build step. This is untested and added only for some shot at completeness.

%.o : %.cpp
    python macros.py $< | g++ -x cpp -c - -o $@
like image 148
Jon Purdy Avatar answered Sep 30 '22 14:09

Jon Purdy


If a makefile isn't conventional enough for you, you could get by with cleverly-written macros.

class FooBarClass
{
    DEFINE_BORING_METHODS( FooBarClass )

    /* interesting functions begin here */
}

I very frequently see this done to implement the boilerplate parts of COM classes.

But if you want something that's neither make nor macro, then I don't know what you could possibly mean.

like image 35
JSBձոգչ Avatar answered Sep 30 '22 14:09

JSBձոգչ