solvingPuzzles
solvingPuzzles

Reputation: 8889

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.

Upvotes: 6

Views: 13253

Answers (3)

John Slade
John Slade

Reputation: 13042

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.

Upvotes: 6

Aniket Inge
Aniket Inge

Reputation: 25695

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?

Upvotes: 7

hobbs
hobbs

Reputation: 239722

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.

Upvotes: 17

Related Questions