Search code examples
cgccstatic-analysisdead-code

Find unused functions in a C project by static analysis


I am trying to run static analysis on a C project to identify dead code i.e functions or code lines that are never ever called. I can build this project with Visual Studio .Net for Windows or using gcc for Linux. I have been trying to find some reasonable tool that can do this for me but so far I have not succeeded. I have read related questions on Stack Overflow i.e this and this and I have tried to use -Wunreachable-code with gcc but the output in gcc is not very helpful. It is of the following format

/home/adnan/my_socket.c: In function ‘my_sockNtoH32’: 
/home/adnan/my_socket.c:666: warning: will never be executed

but when I look at line 666 in my_socket.c, it's actually inside another function that is being called from function my_sockNtoH32() and will not be executed for this specific instance but will be executed when called from some other functions.

What I need is to find the code which will never be executed. Can someone plz help with this?

PS: I can't convince management to buy a tool for this task, so please stick to free/open source tools.


Solution

  • When GCC says "will never be executed", it means it. You may have a bug that, in fact, does make that dead code. For example, something like:

    if (a = 42) {
        // some code
    } else {
        // warning: unreachable code
    }
    

    Without seeing the code it's not possible to be specific, of course.

    Note that if there is a macro at line 666, it's possible GCC refers to a part of that macro as well.