cmakefilecflags

Which rules should use CFLAGS in GNU make


In my makefile for a C project, I have set the CFLAGS variable as follows -

CFLAGS=-ansi -pedantic -Wall -Wextra -O2 -isystem $(SQLITEDIR)

I expected this variable to be used in the rule for building object files since the flags affect the compilation step

However, in the GNU make manual

https://www.gnu.org/software/make/manual/make.html#Using-Implicit

I see the following example -

foo : foo.o bar.o
    cc -o foo foo.o bar.o $(CFLAGS) $(LDFLAGS)

I think this is a rule for the linking step so I understand it why it include LDFLAGS, but what is the purpose CFLAGS here?


Solution

  • (I am guessing that you are using GNU make on some Linux system)

    You are right in your use of CFLAGS (but I would add -g there). But I am not sure you need -isystem $(SQLITEDIR), it probably can be -I $(SQLITEDIR) instead. The -isystem directory option to GCC is rarely useful.

    Read first the documentation about Invoking GCC, assuming you are using the GCC compiler. BTW, you could have CC= gcc in your Makefile. If your compiler is not GCC but something else (e.g. Clang/LLVM) read its documentation.

    Then, run make -p to understand the builtin rules of your GNU make (there are many of them). You'll find out that many builtin rules are using CFLAGS etc. And that is why it is simpler to have a CFLAGS variable in your Makefile; if possible, take advantage of some builtin rules known to make.

    BTW, you could avoid using any builtin rules and variables, but that is poor taste.

    The POSIX standard defines some options understood by cc and by make (and some minimal rules for make). Both GCC and GNU make have much more. Read documentation of GNU make.

    CFLAGS usually contain some (optimization or other) flags (e.g. -O or -g, or -pthread) which are also relevant at the linking step (assuming you link with gcc, which will invoke ld). That is why you usually link using gcc (as $(CC) in your recipe) with both LDFLAGS and CFLAGS.

    You could use make --trace or even remake (as remake -x) to debug your Makefile.