Search code examples
cgcccompiler-flags

GCC Wunused-variable warns for used variable


I am using GCC version 8.2 On several pieces of code, I use small functions. On each one of the functions, I have tests (i.e. Unity framework tests). The tests are defined as #define macros, testing very specific things. For instance, if a number if positive.

Now, when compiling the code using -Wextra flag, I am getting warning about unused variables, although I am using them on the defined macros.

The question is, GCC does not recognize a macro as using a variable, or am I missing something?

Example:

    #define compare(a,b) ( ((a) == (b)) ? 1 : 0 )
    ...
    void f() {
        int a;
        a = f1();
        if(compare(a,123))
            printf("It works");
    }

In this case, GCC would warning about unused variable a, although it is being used by the macro (besides being attributed a value by function f1()).


Solution

  • This is not the case, at least with the example you supplied. Here is a Minimal, Complete, and Verifiable demonstration:

    #include <stdio.h>
    
    #define compare(a,b) ( ((a) == (b)) ? 1 : 0 )
    
    int f1() {
        return 42;
    }
    
    void f() { // your code
        int a;
        a = f1();
        if (compare(a, 123))
            printf("It works");
    }
    
    int main(int argc, char *argv[]) {
        f();
        return 0;
    }
    

    When compiled with gcc -Wall -Wunused (yes, this is redundant) using gcc 8.2 or 7.3 there are no warnings or errors.