1

I'm compiling with a command:

gcc grep.c -std=c99 -g -Winit-self -pedantic -w -o main2 && ./main2 lib text.txt

and I wish to receive warnings for initialized but not used variables and functions.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
tomashauser
  • 561
  • 3
  • 16

2 Answers2

2

If you use -Wunused-variable it will warn for unused variables. But I recommend using -Wall -Wextra. Then you will get that for free with a bunch of other stuff.

When it comes to unused functions I refer to this: GCC -Wunused-function not working (but other warnings are working)

klutt
  • 30,332
  • 17
  • 55
  • 95
  • I don't know what's wrong. I'm using gcc grep.c -std=c99 -g -Winit-self -Wextra -Wall -Wunused-variable -pedantic -w -o meyn && ./meyn lib text.txt and it just doesn't tell me that variables are declared and initialized but unused. – tomashauser Nov 23 '19 at 15:45
  • It might be that initializing a variable may be considered use. There is further a difference between local and global variables. Global non-static variables are always considered used, possibly by other modules, which the compiler can't track. – Paul Ogilvie Nov 23 '19 at 16:10
  • For functions it is the same. Non-static functions could be used by other modules and so cannot be tracked as used or not by the compiler. The linker could, but the linker can't check use in the module where the function is declared. – Paul Ogilvie Nov 23 '19 at 16:12
  • Iirc, you have to turn on optimization to get those warnings, and functions need to be static. – Shawn Nov 23 '19 at 16:12
1

You can use the -Wunused-but-set-variable option to warn for these.

test.c:

int main(void)
{
    int c = 0;
    c = 3;
}

Example:

$ gcc test.c -Wunused-but-set-variable -o test
test.c: In function ‘main’:
test.c:3:9: warning: variable ‘c’ set but not used [-Wunused-but-set-variable]
     int c = 0;
         ^
S.S. Anne
  • 15,171
  • 8
  • 38
  • 76