C++ Generating code with macro

1 minute read

In order to avoid repetition of code, which means a big No to copy-and-paste code, I need to put similar code into a macro, or a function. Considering this, macro wins over the choice of using C++ function. This is not something new, absolutely not but it was so clumsy for my first and second attempts. Therefore, this post summarizes hopefully in a clear manner what is needed to achieve “code generation”.

Everything you should know about C/C++ marco is listed here Marcos. In particular, I refer to the subsection Marcos - Concatenation.

In this post, I will describe here some simple code with generating some function declaration. The first thing first, I create Test.hpp file to host macros. Line 2-4 defines a dictionary that contains

#pragma once
#define MY_MACRO_DICTIONARY(macro) \
	macro(Integer, integer, int, int ) \
	macro(Float, float, float, float ) \

#define MY_DECLARE_GENERATED_FUNCS(name, kname, in_type, out_type) \
	\
	 out_type sum_two_numbers_ ## name(in_type a, in_type b) \
	{ \
		return a + b; \
	} \
	\
   out_type substract_two_numbers_ ## name(in_type a, in_type b) \
	{ \
		return a - b; \
	} \

 MY_MACRO_DICTIONARY(MY_DECLARE_GENERATED_FUNCS)
#undef MY_DECLARE_GENERATED_FUNCS
#undef MY_MACRO_DICTIONARY

The code is self-explanatory I think but Line 8 and Line 13 use ** ## name** to concatenate the left and the right tokens with the argument name as token.

The last piece of this puzzle is the Test.cpp that includes Test.hpp and use the generated functions.

#include <iostream>
#include &quot;generate_macro.hpp&quot;

int main()
{
	sum_two_numbers_Float(1.0, 2.0);
	return sum_two_numbers_Integer(1, 2);
}

Notes By the way, there is a link which describes how to wrap your code block in Wordpress here. And of course, you should enable writing in Markdown for your site as described here

Tags: ,

Updated: