I'm trying to find unused functions in my codebase by using GCC's -Wunused-function
flag.
As I would expect, compiling the below code with gcc -Wall -Wunused-function main.cpp
prints an unused variable
warning:
warning: unused variable ‘x’ [-Wunused-variable]
However, the compiler doesn't give an unused-function
warning.
What do I have to do to make GCC notice the unused function foo()
?
// main.cpp
void foo(){ } //should (but doesn't) trigger 'unused function' warning
int main (int argc, char **argv){
int x; //correctly triggers 'unused variable' warning
return 0;
}
Remember, I do want unused function warnings. This is not a "how do I get rid of warnings" question.
A non-static function is never considered "unused" because its symbol is exported and available to be used by other compilation units, which is something that gcc can't detect. -Wunused-functions
is only documented to warn about static functions that are declared but not called.
from the gcc documentation:
-Wunused-function: Warn whenever a static function is declared but not defined or a non-inline static function is unused. This warning is enabled by -Wall.
As you can see, you've defined and declared a non-static function. Also your function isn't being inlined(for which you need to use -O3
optimization).
I am not sure what you're asking for exists in gcc, as of yet. :-) But its open source.. maybe you can implement it?
You can find unused non-static functions using linker optimisation.
I compiled your main.cpp with
gcc -ffunction-sections -fdata-sections -Wl,--gc-sections -Wl,--print-gc-sections main.cpp
And the output
/usr/bin/ld: Removing unused section '.text._Z3foov' in file '/tmp/cc9IJvbH.o'
Shows that foo()
is unused and the linker could remove it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With