Search code examples
cgccclangunused-variables

How to find irrelevant unused attributes?


While reading parts of the code of a big C project, I found some arguments that were marked as unused but were in fact used in the function.

I thought about grepping the unused attributes but there are too many of them to manually verify if they are really unused.

My question is the following: is there a way to ask to gcc (or clang) if any attributes are not justified or not applied? Basically, for that kind of code:

int f(int arg __attribute__((unused))) {
    return arg + 2;
}

I would like a warning telling my that my argument is not unused.


Solution

  • I can't really take credit for this, as I stumbled upon it at http://sourcefrog.net/weblog/software/languages/C/unused.html. It causes UNUSED variables to give compiler errors when you attempt to use them.

    #ifdef UNUSED 
        // Do notthing if UNUSED is defined
    #elif defined(__GNUC__) 
    // Using the gcc compiler - do the magic!
    #define UNUSED(x) UNUSED_ ## x __attribute__((unused)) 
    #elif defined(__LCLINT__) 
    #define UNUSED(x) /*@unused@*/ x 
    #else 
    // unknown compiler - just remove the macro
    #define UNUSED(x) x 
    #endif
    

    It wont help you find unused variables, but once found you can ensure they really are unused.