Keeping Things Modular With include

The GNU Make include directive lets you include one Makefile in another. One benefit of this is you can more easily re-use your configurations. If you have common behavior patterns that you employ in many places or projects, you can use include to avoid having to rewrite the rules repeatedly.

For example, you might put the following into /usr/local/include/make.def_vars:

CPPFLAGS = -Wall -Wextra -pedantic
ifdef NDEBUG
    CPPFLAGS += -O3
else
    CPPFLAGS += -g
    CPPFLAGS += -D_GLIBCXX_DEBUG
    CPPFLAGS += -fprofile-arcs -ftest-coverage
    CPPFLAGS += -Wundef -Wshadow -Wpointer-arith -Wcast-qual -Wwrite-strings
    CPPFLAGS += -Wconversion -Wsign-compare -Wswitch-enum -Wunused
    CPPFLAGS += -Wshorten-64-to-32 -Woverloaded-virtual -Winline
    CPPFLAGS += -Wno-endif-labels -Wcast-align -Wredundant-decls -Winvalid-pch
endif

To use these settings in a new project all you need do is add the following to your project's Makefile:

include make.def_vars

Not only can using the include directive help make your Makefiles simpler, more modular and more maintainable, it can also provide a simple mechanism for implementing project-wide or organization-wide build policies. You can put a set of common configuration settings in, say, /usr/local/include/make.policy, and require all projects to include make.policy.

If GNU Make's default search path is inadequate, you can use the -I command-line option to point to your Makefile repository.

A second, more subtle benefit of the include directive is you can use it to defer fixing your GNU Make rules until runtime. You can use your Makefile to generate a Makefile from existing files and conditions and then include that in your Makefile. While a certain amount of this behavior is supported by the GNU Make functions, using the include directive is simpler in some contexts. In particular, the include directive makes it simple to use GNU Make to automatically generate the dependencies for the files that it is making, the topic of the section called “Identifying Dependencies Automatically”.