/* 限定只有在定义了__unix__的情况下才能成功编译 */
#ifndef __unix__
#error "This section will only work on UNIX systems"
#endif
/* 插入指定的文件 */
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
/* 两值中的最小值 */
#define min(a,b) ((a) < (b) ? (a) : (b))
/* 替换是递归式的 */
#define TANKARD TSIZE
#define TSIZE 100
/* 删除宏定义 */
#define MLKEYVAL 889
#undef MLKEYVAL
/* 含参数的宏定义,宏名和括号间不能有空格 */
#define decint(a) (a-1)
#define incint (a) (a+1) // 错误
/* 宏参数前加上“#”可将其“字符串化” */
#define MONCK(ARGTERM) \
printf("The term " #ARGTERM " is a string\n");
/* 宏内部连接 */
#define frontback "frontback"
#define PASTE(a,b) a##b
/* 可变参数宏 */
#define prnt(...) printf(__VA_ARGS__);
#define errout(a,b,...) \
fprintf(stderr, "File:%s Line:%d ", a, b); \
fprintf(stderr, __VA_ARGS__); \
fflush(stderr);
#define errexit(fmt, ...) do { \
fprintf(stderr, fmt"\n", ##__VA_ARGS__); \
exit(EXIT_FAILURE); \
} while (0)
int main(void) {
prnt("min=%d\n", min(2,3));
prnt("TANKARD=%d\n", TANKARD);
#ifndef MLKEYVAL
prnt("MLKEYVAL is undef\n");
#else
# define NOKEYVAL /* 可以定义没有值的宏 */
#endif
#if !defined(NOKEYVAL)
prnt("NOKEYVAL is def\n");
#endif
printf("decint(10)=%d\n", decint(10));
MONCK("a+b=c");
MONCK(123);
printf("PASTE(front,back)=%s\n", PASTE(front,back));
errout(__FILE__, __LINE__, "Func:%s\n", __func__);
errexit("exit");
return 0;
}
测试:
:~$ ./pretreatment
min=2
TANKARD=100
MLKEYVAL is undef
NOKEYVAL is def
decint(10)=9
The term "a+b=c" is a string
The term 123 is a string
PASTE(front,back)=frontback
File:pretreatment.c Line:64 Func:main
exit