2010-11-04 22 views
10

考慮以下兩個宏:抑制「ISO C99需要休息參數用於」

#define PNORM(v, s, ...) { \ 
    if(VERBOSITY_CHECK(v)) { \ 
    if((errno = pthread_mutex_lock(&server.output_mutex))) { \ 
     PERROR_LOCKFREE(normal, "\tpthread_mutex_lock failed on output_mutex.\r\n") ; \ 
    } \ 
    fprintf(stdout, s, ## __VA_ARGS__) ; \ 
    fflush(stdout) ; \ 
    if((errno = pthread_mutex_unlock(&server.output_mutex))) { \ 
     PERROR_LOCKFREE(normal, "\tpthread_mutex_unlock failed on output_mutex.\r\n") ; \ 
    } \ 
    } \ 
} 

#define PERROR_LOCKFREE(v, s, ...) { \ 
    if(VERBOSITY_CHECK(v)) { \ 
    PERRNO ;\ 
    fprintf(stderr, s, ## __VA_ARGS__) ; \ 
    fflush(stderr) ; \ 
    } \ 
} 

現在考慮一個例子使用這些:

PNORM(verbose, "\tSomeText [%d] More [%p]\r\n", 0, ptr) ; 

當使用-pedantic選項編譯-std = c99我得到這個錯誤很多次:

mycode.c:410:112: warning: ISO C99 requires rest arguments to be used 

編譯器是正確的抱怨這個,但有一個si多少方式我可以壓制這個警告,因爲我不關心它?

回答

9

s參數與可變參數組合在一起,以便始終至少有一個參數作爲省略號的一部分。這也可以讓你避免使用,##擴展GCC的:

#define PNORM(v, ...) { \ 
    if(VERBOSITY_CHECK(v)) { \ 
    if((errno = pthread_mutex_lock(&server.output_mutex))) { \ 
     PERROR_LOCKFREE(normal, "\tpthread_mutex_lock failed on output_mutex.\r\n") ; \ 
    } \ 
    fprintf(stdout, __VA_ARGS__) ; \ 
    fflush(stdout) ; \ 
    if((errno = pthread_mutex_unlock(&server.output_mutex))) { \ 
     PERROR_LOCKFREE(normal, "\tpthread_mutex_unlock failed on output_mutex.\r\n") ; \ 
    } \ 
    } \ 
} 

#define PERROR_LOCKFREE(v, ...) { \ 
    if(VERBOSITY_CHECK(v)) { \ 
    PERRNO ;\ 
    fprintf(stderr, __VA_ARGS__) ; \ 
    fflush(stderr) ; \ 
    } \ 
} 
1

你可以disable就在你的宏附近發出警告,或者在GCC中完全禁止使用pragma Warnings這個警告。你也可以不使用-pedantic,因爲它是好學的。

+2

迂腐是一個很好的功能,用它來幫助你的代碼捕獲的小錯誤。警告不應該被忽略。 – 2010-11-04 22:01:08

+0

@David:當然,但問題是「我怎麼忽略這個警告。」 '-pedantic'實際上僅用於捕獲gcc依賴項。 ''WALL'幾乎可以捕捉到所有可能被警告捕獲的錯誤。 – nmichaels 2010-11-04 23:04:51

+0

這個答案真的不能禁用這個警告。從理論上講,至少我的gcc版本不支持'pragma Warnings'。 – 2016-11-15 23:30:05

2

##令牌與__VA_ARGS__組合是gcc擴展,它不是ISO C99的一部分。這就是爲什麼你會收到警告。

1

取決於什麼是你簡單。在P99有P99 conditionals,將允許你做這樣

#define USER_MACRO(...) P99_IF_DEC_LE(P99_NARG(__VA_ARGS__),2)(USER_MACRO2(__VA_ARGS__))(USER_MACRO3(__VA_ARGS__)) 

因此就沒有必要爲,##擴展的gcc。

+0

這應該是被接受的答案。更優雅。 – Barry 2017-09-25 22:43:16