simplecpp
simplecpp copied to clipboard
Defect: Prepocessor fails to expand x-macro macro parameter
cppcheck fails to preprocess the code below:
> cppcheck --version
Cppcheck 2.3
> cppcheck -E main.c
main.c:12:0: error: failed to expand 'COLOR_SET', Wrong number of parameters for macro 'ALL_COLORS'. [preprocessorErrorDirective]
#define COLOR_SET ALL_COLORS(WARM_COLORS)
^
main.c:
#define ALL_COLORS(warm_colors) \
X(Blue) \
X(Green) \
X(Purple) \
warm_colors
#define WARM_COLORS \
X(Red) \
X(Yellow) \
X(Orange)
#define COLOR_SET ALL_COLORS(WARM_COLORS)
#define X(color) #color,
COLOR_SET
gcc handles it fine:
> gcc -E main.c
# 1 "main.c"
# 1 "<built-in>"
# 1 "<command-line>"
# 1 "/usr/include/stdc-predef.h" 1 3 4
# 1 "<command-line>" 2
# 1 "main.c"
# 16 "main.c"
"Blue", "Green", "Purple", "Red", "Yellow", "Orange",
A work around for this issue is to use an EVAL() macro:
#define EVAL(...) __VA_ARGS__
#define ALL_COLORS(warm_colors) \
X(Blue) \
X(Green) \
X(Purple) \
warm_colors
#define WARM_COLORS \
X(Red) \
X(Yellow) \
X(Orange)
#define COLOR_SET ALL_COLORS(EVAL(WARM_COLORS))
#define X(color) #color,
COLOR_SET
> cppcheck -E main.c
"Blue" , "Green" , "Purple" , "Red" , "Yellow" , "Orange" ,
ok.