6

我有以下代码,在使用 gcc-4.6 编译时收到警告:

警告:变量“状态”已设置但未使用 [-Wunused-but-set-variable]

#if defined (_DEBUG_)
#define ASSERT       assert
#else                           /* _DEBUG_ */
#define ASSERT( __exp__ )
#endif   

static inline void cl_plock(cl_plock_t * const p_lock)
{
        status_t status;
        ASSERT(p_lock);
        ASSERT(p_lock->state == INITIALIZED);

        status = pthread_rwlock_unlock(&p_lock->lock);
        ASSERT(status == 0); 
}

当 _DEBUG_ 标志未设置时,我会收到警告。任何想法如何解决此警告?

4

3 回答 3

3

您可以将ASSERT宏更改为:

#if defined (_DEBUG_)
#define ASSERT       assert
#else                           /* _DEBUG_ */
#define ASSERT( exp ) ((void)(exp))
#endif   

如果表达式没有副作用,那么它仍然应该被优化,但它也应该抑制警告(如果表达式确实有副作用,那么你会在调试和非调试构建中得到不同的结果,而你没有'也不想要!)。

于 2011-07-06T06:24:28.473 回答
2

关闭未使用变量警告的编译器选项是-Wno-unused. 要在更精细的级别上获得相同的效果,您可以使用如下诊断编译指示

int main()
{
  #pragma GCC diagnostic ignored "-Wunused-variable"
  int a;
  #pragma GCC diagnostic pop
  // -Wunused-variable is on again
  return 0;
}

当然,这不是可移植的,但您可以对 VS使用类似的东西。

于 2011-07-05T13:27:59.623 回答
1

status你可以用一个#ifdef子句包围变量声明。

#ifdef _DEBUG_
    status_t status
#endif

编辑:您还必须包围通话:

#ifdef _DEBUG_
    status = pthread_rwlock_unlock(&p_lock->lock);
#else
    pthread_rwlock_unlock(&p_lock->lock);
#endif

或者您可以关闭错误消息。

于 2011-07-05T13:19:55.867 回答