2011-07-05 35 views
5

我有,并同时用gcc-4.6编译它下面的代码,我得到警告:Wunused,但设置变量警告处理

警告:变量“状态”设置,但不使用[-Wunused-但设置变量]

#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

你可以改变你的ASSERT宏:

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

如果表达式没有副作用,那么它应该还是可以优化掉了,但也要抑制警告(如果表达式确实有副作用-effects,那么在调试和非调试版本中你将得到不同的结果,你也不想这么做!)。

+0

你的副作用是什么意思? – alnet

+1

@alnet:具有副作用的表达式是改变某些内容的表达式,例如'ASSERT(i ++);'。 – caf

+0

我现在有相关的问题:) [链接](http://stackoverflow.com/questions/6641538/has-no-member-compilation-error) – alnet

1

您可以用#ifdef子句包围status的变量声明。

#ifdef _DEBUG_ 
    status_t status 
#endif 

编辑:你必须围绕呼叫也:

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

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

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.

+0

如果你要这样做,那么你可以在声明中使用'__attribute __((未使用的))'注释。 – caf

相关问题