Wunused-but-set-variable警告处理

时间:2011-07-05 13:16:38

标签: c gcc gcc-warning

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

  

警告:变量'status'已设置但未使用[-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_时 标志未设置我收到警告。 任何想法如何解决此警告?

3 个答案:

答案 0 :(得分:3)

您可以将ASSERT宏更改为:

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

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

答案 1 :(得分:2)

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

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

当然,这不是便携式的,但您可以使用something similar作为VS。

答案 2 :(得分: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

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