Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GCC -Wunused-function not working (but other warnings are working)

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.

like image 423
solvingPuzzles Avatar asked Nov 04 '12 23:11

solvingPuzzles


3 Answers

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.

like image 181
hobbs Avatar answered Nov 15 '22 06:11

hobbs


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?

like image 27
Aniket Inge Avatar answered Nov 15 '22 07:11

Aniket Inge


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.

like image 38
JohnTESlade Avatar answered Nov 15 '22 07:11

JohnTESlade