Do I need to pass CFLAGS explicitly to gcc?

11,646

Solution 1

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.

Solution 2

I believe CFLAGS is implicitly passed to the compiler command line by the makefile via the default compilation rule... Yet the CFLAGS can be overridden with custom flags so that each compilation command will take it and use.

Solution 3

You can test it easily:

$ cat cflags.mak 
CFLAGS = -wrong

foo.o: foo.c

$ make -f cflags.mak 
cc -wrong   -c -o foo.o foo.c
cc: unrecognized option '-wrong'

So you can see it used the value of CFLAGS even though it was not explicitly specified in a rule; thus it is implicit.

But if you do specify your own rule for compiling .c files, you have to include it if you want it used:

$ cat cflags.mak 
CFLAGS = -wrong

foo.o: foo.c
    gcc -c $<
$ make -f cflags.mak 
gcc -c foo.c

Here I provided my own rule for .c files which did not include CFLAGS, so CFLAGS was not used.

So the bottom line is if you rely on the built-in make rule for compiling .c files, CFLAGS will be included implicitly. But if you override that rule, you have to include it explicitly if you still want it to be used.

Solution 4

It means that there are implicit make rules, that use the CFLAGS, you can use. So you can write a one line makefile with:

CFLAGS=-O2

if you later do:

make filename

(omitting extension) it will use an implicit rule that references the CFLAGS to convert you source file .c in an executable, so you don't need to write an explicit build statement for simple builds.

E.g. if you prepared a source name file.c it will build it with an implicit rule like:

$GCC $CFLAGS file.c -o file $LDFLAGS

see: GNU make documentation

Share:
11,646
Foo Bar
Author by

Foo Bar

Updated on June 12, 2022

Comments

  • Foo Bar
    Foo Bar almost 2 years

    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?