Wunused-but-set-variable warning treatment

2019-04-28 09:38发布

I have the following code, and while compiling it with gcc-4.6 I get warning:

warning: variable ‘status’ set but not used [-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); 
}

When _DEBUG_ flag isn't set I get the warning. Any ideas how can I workaround this warning?

3条回答
太酷不给撩
2楼-- · 2019-04-28 10:16

The compiler option to turn off unused variable warnings is -Wno-unused. To get the same effect on a more granular level you can use diagnostic pragmas like this:

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

This is, of course, not portable but you can use something similar for VS.

查看更多
做个烂人
3楼-- · 2019-04-28 10:18

You could surround the variable declaration of status with a #ifdef clause.

#ifdef _DEBUG_
    status_t status
#endif

EDIT: You have to surround the call also:

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

or you can switch off the error message.

查看更多
祖国的老花朵
4楼-- · 2019-04-28 10:25

You can change your ASSERT macro to:

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

If the expression has no sideeffects, then it should still be optimised out, but it should also suppress the warning (if the expression does have side-effects, then you would get different results in debug and non-debug builds, which you don't want either!).

查看更多
登录 后发表回答