Boost 预处理器(它适用于 C 和 C++,尽管 Boost 作为一个整体是一个 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