Macro Options

To make the compiler happy, I need to recount the parameters passed to A() , otherwise gcc raises " warning: ISO C99 requires rest arguments to be used " when the pedantry flag is on and only one parameter is passed

 #include <stdio.h> /* Count params */ #define N_ARGS(...) N_ARGS_IMPL(__VA_ARGS__,n,n,n,n,n,n,n,n,n,1,1) #define N_ARGS_IMPL(_0,_1,_2,_3,_4,_5,_6,_7,_8,_9,N,...) N #define A_fmt_void #define A_arg_void /* link */ #define A_fmt_link_1(fmt) " href=\""fmt"\"" #define A_fmt_link_n(fmt, ...) " href=\""fmt"\"" #define A_fmt_link_N(n, ...) A_fmt_link_##n(__VA_ARGS__) #define A_fmt_link_X(n, ...) A_fmt_link_N(n,__VA_ARGS__) #define A_fmt_link(...) A_fmt_link_X(N_ARGS(__VA_ARGS__), __VA_ARGS__) #define A_arg_link_1(fmt) #define A_arg_link_n(fmt, ...) , __VA_ARGS__ #define A_arg_link_N(n, ...) A_arg_link_##n(__VA_ARGS__) #define A_arg_link_X(n, ...) A_arg_link_N(n,__VA_ARGS__) #define A_arg_link(...) A_arg_link_X(N_ARGS(__VA_ARGS__), __VA_ARGS__) /* text */ #define A_fmt_text_1(fmt) fmt #define A_fmt_text_n(fmt, ...) fmt #define A_fmt_text_N(n, ...) A_fmt_text_##n(__VA_ARGS__) #define A_fmt_text_X(n, ...) A_fmt_text_N(n,__VA_ARGS__) #define A_fmt_text(...) A_fmt_text_X(N_ARGS(__VA_ARGS__), __VA_ARGS__) #define A_arg_text_1(fmt) #define A_arg_text_n(fmt, ...) , __VA_ARGS__ #define A_arg_text_N(n, ...) A_arg_text_##n(__VA_ARGS__) #define A_arg_text_X(n, ...) A_arg_text_N(n,__VA_ARGS__) #define A_arg_text(...) A_arg_text_X(N_ARGS(__VA_ARGS__), __VA_ARGS__) /* macro */ #define A(link, text) \ printf("<a"A_fmt_##link">"A_fmt_##text"</a>\n" A_arg_##link A_arg_##text) int main(void) { A(link(), void); A(void, text()); A(link("http://www.google.es"), void); A(link("%s/%s", "http://www.google.es", "home"), text("Visit google")); A(void, text("%s today", "Visit google")); A(link("http://%s/%s", "www.google.es", "home"), text("%s today", "Visit google")); A(void,void); return 0; } 

With this N_ARGS implementation N_ARGS I can only use 10 parameters, is there another way to check if there are more than one parameter in a macro without any restrictions?

I know the extension , ## __VA_ARGS__ gcc, but I want to avoid warnings

+6
source share
1 answer

Finally, I fixed the use of __ extension__

 #include <stdio.h> #define A_fmt_void #define A_arg_void #define A_fmt_link(fmt, ...) " href=\""fmt"\"" #define A_arg_link(fmt, ...) , ## __VA_ARGS__ #define A_fmt_text(fmt, ...) fmt #define A_arg_text(fmt, ...) , ## __VA_ARGS__ #define A(link, text) \ __extension__ printf("<a" A_fmt_##link ">" A_fmt_##text "</a>\n" A_arg_##link A_arg_##text) int main(void) { A( link("%s", "http://wwww.google.com"), text("%s", "Visit google") ); A( link("http://wwww.google.com"), void ); A( void, text("Visit google") ); A( void, void ); return 0; } 

This prevents warnings when the pedantry flag is on :)

+1
source

All Articles