Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get g++ to warn on unused member variables

Tags:

c++

g++

g++ generates warnings for unused local variables. Is it possible to have g++ warn for unused class member variables and/or global variables?

class Obj {
 public:
  Obj(int a, int b) : num1(a), num2(b) {}
  int addA(int i) {
    return i + num1;
  }

 private:
  int num1;
  int num2;
};

How do I get g++ to warn me that num2 is unused?

UPDATE: I am currently compiling with:

g++ -Wall -Wextra -pedantic *.cc -o myprogram 
like image 895
nic Avatar asked May 02 '14 20:05

nic


People also ask

How do I get rid of the unused variable warning?

Solution: If variable <variable_name> or function <function_name> is not used, it can be removed. If it is only used sometimes, you can use __attribute__((unused)) . This attribute suppresses these warnings.

How do you handle unused variables in Python?

To suppress the warning, one can simply name the variable with an underscore ('_') alone. Python treats it as an unused variable and ignores it without giving the warning message.

What are unused variables?

Unused variables are a waste of space in the source; a decent compiler won't create them in the object file. Unused parameters when the functions have to meet an externally imposed interface are a different problem; they can't be avoided as easily because to remove them would be to change the interface.

Why is unused variable an error?

Unused variable warnings are emitted during compiletime and should be a hint to you as the developer, that you might have forgotten to actually process a value that you have bound to a name. Thats the main reason for the warning.


2 Answers

Clang's -Wunused-private-field enables the warning you're asking for. On your code base, it shows:

$ clang -Wunused-private-field /tmp/nic.cpp  
/tmp/nic.cpp:10:22: warning: private field 'num2' is not used [-Wunused-private-field]
             int num2;
                 ^
1 warning generated.
like image 188
David Faure Avatar answered Sep 18 '22 14:09

David Faure


I'm not aware of any such warning. Additionally I'll speculate that the reason it doesn't exist is because it can't be reliably generated in all cases, so they elected to not spend effort making it work for some subset of cases. For example, if the class friends another function that's in a library, the compiler would have no way of knowing if that library mutated any particular class attribute or not.

like image 44
Mark B Avatar answered Sep 17 '22 14:09

Mark B