gccmakefileimplicitcflags

Do I need to pass CFLAGS explicitly to gcc?


I read a lot of tutorials about CFLAGS and also looked in the official docs. Everywhere they say CFLAGS is implicit but still pass it explicitly in their example makefile to the compiler:

CFLAGS=-O2
gcc $(CFLAGS) -c foo.c -o foo.o

So, what does the term "implicit" mean in this context? If I declare CFLAGS=-O2 in my makefile and later just say gcc -c foo.c -o foo.o, will -O2 be active or not (so, is it really implicit)? If so, why do all tutorials (including official docs) still pass it explicitly in their examples?


Solution

  • Everywhere they say CFLAGS is implicit but still pass it explicitly in their example makefile to the compiler.

    gcc does not use CFLAGS environment variable. See Environment Variables Affecting GCC.

    CFLAGS is a conventional name for a Makefile variable with C-compiler flags and it is used by implicit make rules. See Variables Used by Implicit Rules for more details.

    If you use your own make rules instead of the built-in ones, you do not need to use CFLAGS at all. Although it is a useful convention to do so because people are familiar with the conventional make variable names.