Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C/C++ Macro expansion vs. Code generation

Both Macro expansion & Code generation have pros & cons. What's your favorite approach and why? When should we choose one over the other? Please kindly advise. Thank you!

Macro expansion can be very handy & helpful: http://dtemplatelib.sourceforge.net/table.htm

vs

While Code generation gives you plenty of nice code: http://code.google.com/p/protobuf/ http://incubator.apache.org/thrift/

like image 226
Viet Avatar asked Nov 27 '09 09:11

Viet


2 Answers

For c++ I prefer either template metaprogramming or code generation over macros, but macros still have their uses.

The example you have given with dbtemplatelib could be covered with c++0x Variadic Templates, with additional benefits like type checking etc.

like image 70
Gunther Piez Avatar answered Oct 04 '22 01:10

Gunther Piez


In C or C++, macro expansion is notoriously difficult to debug. On the other hand, writing a code generator is easier to debug because it's a separate program in itself.

However, you should be aware that this is merely a limitation of the C preprocessor. For example, in the Lisp family of languages, macro expansion is code generation, they're exactly the same thing. To write a macro, you write a program (in Lisp) to transform S-expression input into another S-expression, which is then passed to the compiler.

like image 26
Greg Hewgill Avatar answered Oct 04 '22 01:10

Greg Hewgill