Automatic C++ Source Code Generation with clang

By Sergei Sadovnikov

Almost every C/C++ programmer eventually runs into a situation when they have to write a lot of boilerplate code. Enum to string conversion (and vice versa), data serialization/deserialization, remoting proxy/stubs are the most common cases. There is a number of different techniques to reduce the effort to produce this kind of code, such as macros metaprogramming, templates metaprogramming, tricks with files inclusion, special DSL with converters and so on.

This talk introduces one such technique based on clang 3.9 front-end and its special 'libtooling' library. It describes an easy method to analyze the existing C++ sources and to produce another set of C++ sources for specified task (for instance, enum to string converters). Development of a clang-based tool "from scratch" is introduced, including command line options analysis, clang compiler invocation, AST investigation, result code generation, etc. Also, the method for custom tool integration into the CMake-based build system is presented. The talk is illustrated with simple examples, which can be useful for making your own custom clang-based tools. Write less code and enjoy!