[Makefile] Difference between CPPFLAGS and CXXFLAGS in GNU Make


Answers

By default, CPPFLAGS will be given to the C preprocessor, while CXXFLAGS will be given to the C++ compiler.

The GNU Make Manual is a good resource for questions like this (see Implicit Variables).

Question

What's the difference between CPPFLAGS and CXXFLAGS in GNU Make?




Try setting CXXFLAGS in addition to CFLAGS.







CFLAGS vs CPPFLAGS

The implicit make rule for compiling a C program is

%.o:%.c
    $(CC) $(CPPFLAGS) $(CFLAGS) -c -o $@ $<

where the $() syntax expands the variables. As both CPPFLAGS and CFLAGS are used in the compiler call, which you use to define include paths is a matter of personal taste. For instance if foo.c is a file in the current directory

make foo.o CPPFLAGS="-I/usr/include"
make foo.o CFLAGS="-I/usr/include"

will both call your compiler in exactly the same way, namely

gcc -I/usr/include -c -o foo.o foo.c

The difference between the two comes into play when you have multiple languages which need the same include path, for instance if you have bar.cpp then try

make bar.o CPPFLAGS="-I/usr/include"
make bar.o CFLAGS="-I/usr/include"

then the compilations will be

g++ -I/usr/include -c -o bar.o bar.cpp
g++ -c -o bar.o bar.cpp

as the C++ implicit rule also uses the CPPFLAGS variable.

This difference gives you a good guide for which to use - if you want the flag to be used for all languages put it in CPPFLAGS, if it's for a specific language put it in CFLAGS, CXXFLAGS etc. Examples of the latter type include standard compliance or warning flags - you wouldn't want to pass -std=c99 to your C++ compiler!

You might then end up with something like this in your makefile

CPPFLAGS=-I/usr/include
CFLAGS=-std=c99
CXXFLAGS=-Weffc++



What is “XX” in CXX in a cmake CMakeLists.txt file.

XX stands for "++" (each X is like a "plus" rotated by 45°), CXX stands for "C++".

Why "CXX"?

  • "C++" is not possible because of macro identifiers limitations (they can't contain a +);
  • "CPP" (for "C Plus Plus") is usually already used to stand for "C PreProcessor".

For example in a GNU Makefile you can define the following "variables":

  • CPPFLAGS : extra flags for the C preprocessor (also used in C++).
  • CFLAGS   : extra flags for the C compiler.
  • CXXFLAGS : extra flags for the C++ compiler.

(Usually you will use CPPFLAGS and CFLAGS for a C project, and CPPFLAGS and CXXFLAGS for a C++ project.)


See also Difference between CPPFLAGS and CXXFLAGS in GNU Make and CFLAGS vs CPPFLAGS.

Also related: Correct C++ file extension (and duplicate links).