Boost Preprocessor ( Boost は全体として C++ ライブラリですが、C だけでなく C++ でも機能します) ライブラリは、この種のタスクに役立ちます。マクロ内で #ifdef を使用する (これは許可されていません) 代わりに、毎回異なるマクロを定義してファイルを複数回インクルードし、ファイルで #ifdef を使用できるようにするのに役立ちます。
次のコードは、max.c に保存されている場合、ファイルの先頭にある MAXES #define にリストされている各単語に対して必要な処理を実行する必要があります。ただし、プリプロセッサは浮動小数点を処理できないため、_MAX 値のいずれかが浮動小数点の場合は機能しません。
(Boost Processor は便利なツールですが、完全に簡単というわけではありません。このアプローチがコピー アンド ペーストよりも優れているかどうかを判断できます。)
#define MAXES (SHRT)(INT)(LONG)(PATH)(DOESNT_EXIST)
#if !BOOST_PP_IS_ITERATING
/* This portion of the file (from here to #else) is the "main" file */
#include <values.h>
#include <stdio.h>
#include <boost/preprocessor.hpp>
/* Define a function print_maxes that iterates over the bottom portion of this
* file for each word in MAXES */
#define BOOST_PP_FILENAME_1 "max.c"
#define BOOST_PP_ITERATION_LIMITS (0,BOOST_PP_DEC(BOOST_PP_SEQ_SIZE(MAXES)))
void print_maxes(void) {
#include BOOST_PP_ITERATE()
}
int main(int argc, char *argv[])
{
print_maxes();
}
#else
/* This portion of the file is evaluated multiple times, with
* BOOST_PP_ITERATION() resolving to a different number every time */
/* Use BOOST_PP_ITERATION() to look up the current word in MAXES */
#define CURRENT BOOST_PP_SEQ_ELEM(BOOST_PP_ITERATION(), MAXES)
#define CURRENT_MAX BOOST_PP_CAT(CURRENT, _MAX)
#if CURRENT_MAX
printf("The max of " BOOST_PP_STRINGIZE(CURRENT) " is %lld\n", (long long) CURRENT_MAX);
#else
printf("The max of " BOOST_PP_STRINGIZE(CURRENT) " is undefined\n");
#endif
#undef CURRENT
#undef CURRENT_MAX
#endif