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

僤鯓⒐⒋嵵緔 提交于 2020-01-14 10:13:24

问题


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.


回答1:


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?




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/13224209/gcc-wunused-function-not-working-but-other-warnings-are-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!