10

考虑以下两个宏:

#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

编译器对此的抱怨是正确的,但有没有一种简单的方法可以抑制这个警告,因为我不关心它?

4

4 回答 4

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 ) ; \
  } \
}
于 2010-11-04T20:57:18.763 回答
2

##与 结合的令牌__VA_ARGS__是不属于 ISO C99 的 gcc 扩展。这就是你收到警告的原因。

于 2010-11-04T20:36:00.857 回答
1

您可以在宏周围禁用pragma Warnings警告,或在 GCC 中完全禁用特定警告。您也不能使用-pedantic,因为它很迂腐。

于 2010-11-04T20:05:10.617 回答
1

取决于对你来说什么是简单的。在 P99 中有P99 条件可以让你做类似的事情

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

因此,不需要,##扩展 gcc。

于 2010-11-04T20:52:34.500 回答