I built this guide because I could never quite wrap my head around Makefiles. They seemed awash with hidden rules and esoteric symbols, and asking simple questions didn’t yield simple answers. To solve this, I sat down for several weekends and read everything I could about Makefiles. I've condensed the most critical knowledge into this guide. Each topic has a brief description and a self contained example that you can run yourself.
588 |If you mostly understand Make, consider checking out the Makefile Cookbook, which has a template for medium sized projects with ample comments about what each part of the Makefile is doing.
589 |Good luck, and I hope you are able to slay the confusing world of Makefiles!
590 |Getting Started
591 |Why do Makefiles exist?
592 |Makefiles are used to help decide which parts of a large program need to be recompiled. In the vast majority of cases, C or C++ files are compiled. Other languages typically have their own tools that serve a similar purpose as Make. Make can also be used beyond compilation too, when you need a series of instructions to run depending on what files have changed. This tutorial will focus on the C/C++ compilation use case.
593 |Here's an example dependency graph that you might build with Make. If any file's dependencies changes, then the file will get recompiled:
594 |
What alternatives are there to Make?
599 |Popular C/C++ alternative build systems are SCons, CMake, Bazel, and Ninja. Some code editors like Microsoft Visual Studio have their own built in build tools. For Java, there's Ant, Maven, and Gradle. Other languages like Go, Rust, and TypeScript have their own build tools.
600 |Interpreted languages like Python, Ruby, and raw Javascript don't require an analogue to Makefiles. The goal of Makefiles is to compile whatever files need to be compiled, based on what files have changed. But when files in interpreted languages change, nothing needs to get recompiled. When the program runs, the most recent version of the file is used.
601 |The versions and types of Make
602 |There are a variety of implementations of Make, but most of this guide will work on whatever version you're using. However, it's specifically written for GNU Make, which is the standard implementation on Linux and MacOS. All the examples work for Make versions 3 and 4, which are nearly equivalent other than some esoteric differences.
603 |Running the Examples
604 |To run these examples, you'll need a terminal and "make" installed. For each example, put the contents in a file called Makefile
, and in that directory run the command make
. Let's start with the simplest of Makefiles:
hello:
606 | echo "Hello, World"
607 | 608 |610 |Note: Makefiles must be indented using TABs and not spaces or
609 |make
will fail.
Here is the output of running the above example:
611 |$ make
612 | echo "Hello, World"
613 | Hello, World
614 | That's it! If you're a bit confused, here's a video that goes through these steps, along with describing the basic structure of Makefiles.
615 |Makefile Syntax
620 |A Makefile consists of a set of rules. A rule generally looks like this:
621 |targets: prerequisites
622 | command
623 | command
624 | command
625 | -
626 |
- The targets are file names, separated by spaces. Typically, there is only one per rule. 627 |
- The commands are a series of steps typically used to make the target(s). These need to start with a tab character, not spaces. 628 |
- The prerequisites are also file names, separated by spaces. These files need to exist before the commands for the target are run. These are also called dependencies 629 |
The essence of Make
631 |Let's start with a hello world example:
632 |hello:
633 | echo "Hello, World"
634 | echo "This line will print if the file hello does not exist."
635 | There's already a lot to take in here. Let's break it down:
636 |-
637 |
- We have one target called
hello
638 | - This target has two commands 639 |
- This target has no prerequisites 640 |
We'll then run make hello
. As long as the hello
file does not exist, the commands will run. If hello
does exist, no commands will run.
It's important to realize that I'm talking about hello
as both a target and a file. That's because the two are directly tied together. Typically, when a target is run (aka when the commands of a target are run), the commands will create a file with the same name as the target. In this case, the hello
target does not create the hello
file.
Let's create a more typical Makefile - one that compiles a single C file. But before we do, make a file called blah.c
that has the following contents:
// blah.c
645 | int main() { return 0; }
646 | Then create the Makefile (called Makefile
, as always):
blah:
648 | cc blah.c -o blah
649 | This time, try simply running make
. Since there's no target supplied as an argument to the make
command, the first target is run. In this case, there's only one target (blah
). The first time you run this, blah
will be created. The second time, you'll see make: 'blah' is up to date
. That's because the blah
file already exists. But there's a problem: if we modify blah.c
and then run make
, nothing gets recompiled.
We solve this by adding a prerequisite:
651 |blah: blah.c
652 | cc blah.c -o blah
653 | When we run make
again, the following set of steps happens:
-
655 |
- The first target is selected, because the first target is the default target 656 |
- This has a prerequisite of
blah.c
657 | - Make decides if it should run the
blah
target. It will only run ifblah
doesn't exist, orblah.c
is newer thanblah
658 |
This last step is critical, and is the essence of make. What it's attempting to do is decide if the prerequisites of blah
have changed since blah
was last compiled. That is, if blah.c
is modified, running make
should recompile the file. And conversely, if blah.c
has not changed, then it should not be recompiled.
To make this happen, it uses the filesystem timestamps as a proxy to determine if something has changed. This is a reasonable heuristic, because file timestamps typically will only change if the files are 661 | modified. But it's important to realize that this isn't always the case. You could, for example, modify a file, and then change the modified timestamp of that file to something old. If you did, Make would incorrectly guess that the file hadn't changed and thus could be ignored.
662 |Whew, what a mouthful. Make sure that you understand this. It's the crux of Makefiles, and might take you a few minutes to properly understand. Play around with the above examples or watch the video above if things are still confusing.
663 |More quick examples
664 |The following Makefile ultimately runs all three targets. When you run make
in the terminal, it will build a program called blah
in a series of steps:
-
666 |
- Make selects the target
blah
, because the first target is the default target
667 | blah
requiresblah.o
, so make searches for theblah.o
target
668 | blah.o
requiresblah.c
, so make searches for theblah.c
target
669 | blah.c
has no dependencies, so theecho
command is run
670 | - The
cc -c
command is then run, because all of theblah.o
dependencies are finished
671 | - The top
cc
command is run, because all theblah
dependencies are finished
672 | - That's it:
blah
is a compiled c program
673 |
blah: blah.o
675 | cc blah.o -o blah # Runs third
676 |
677 | blah.o: blah.c
678 | cc -c blah.c -o blah.o # Runs second
679 |
680 | # Typically blah.c would already exist, but I want to limit any additional required files
681 | blah.c:
682 | echo "int main() { return 0; }" > blah.c # Runs first
683 | If you delete blah.c
, all three targets will be rerun. If you edit it (and thus change the timestamp to newer than blah.o
), the first two targets will run. If you run touch blah.o
(and thus change the timestamp to newer than blah
), then only the first target will run. If you change nothing, none of the targets will run. Try it out!
This next example doesn't do anything new, but is nontheless a good additional example. It will always run both targets, because some_file
depends on other_file
, which is never created.
some_file: other_file
686 | echo "This will always run, and runs second"
687 | touch some_file
688 |
689 | other_file:
690 | echo "This will always run, and runs first"
691 | Make clean
692 |clean
is often used as a target that removes the output of other targets, but it is not a special word in Make. You can run make
and make clean
on this to create and delete some_file
.
Note that clean
is doing two new things here:
-
695 |
- It's a target that is not first (the default), and not a prerequisite. That means it'll never run unless you explicitly call
make clean
696 | - It's not intended to be a filename. If you happen to have a file named
clean
, this target won't run, which is not what we want. See.PHONY
later in this tutorial on how to fix this
697 |
some_file:
699 | touch some_file
700 |
701 | clean:
702 | rm -f some_file
703 | Variables
704 |Variables can only be strings. You'll typically want to use :=
, but =
also works. See Variables Pt 2.
Here's an example of using variables:
706 |files := file1 file2
707 | some_file: $(files)
708 | echo "Look at this variable: " $(files)
709 | touch some_file
710 |
711 | file1:
712 | touch file1
713 | file2:
714 | touch file2
715 |
716 | clean:
717 | rm -f file1 file2 some_file
718 | Single or double quotes have no meaning to Make. They are simply characters that are assigned to the variable. Quotes are useful to shell/bash, though, and you need them in commands like printf
. In this example, the two commands behave the same:
a := one two# a is set to the string "one two"
720 | b := 'one two' # Not recommended. b is set to the string "'one two'"
721 | all:
722 | printf '$a'
723 | printf $b
724 | Reference variables using either ${}
or $()
x := dude
726 |
727 | all:
728 | echo $(x)
729 | echo ${x}
730 |
731 | # Bad practice, but works
732 | echo $x
733 | Targets
734 |The all target
735 | 736 |Making multiple targets and you want all of them to run? Make an all
target.
737 | Since this is the first rule listed, it will run by default if make
is called without specifying a target.
all: one two three
739 |
740 | one:
741 | touch one
742 | two:
743 | touch two
744 | three:
745 | touch three
746 |
747 | clean:
748 | rm -f one two three
749 |
750 | Multiple targets
751 | 752 |When there are multiple targets for a rule, the commands will be run for each target. $@
is an automatic variable that contains the target name.
all: f1.o f2.o
754 |
755 | f1.o f2.o:
756 | echo $@
757 | # Equivalent to:
758 | # f1.o:
759 | # echo f1.o
760 | # f2.o:
761 | # echo f2.o
762 |
763 | Automatic Variables and Wildcards
764 |* Wildcard
765 | 766 |Both *
and %
are called wildcards in Make, but they mean entirely different things. *
searches your filesystem for matching filenames. I suggest that you always wrap it in the wildcard
function, because otherwise you may fall into a common pitfall described below.
# Print out file information about every .c file
768 | print: $(wildcard *.c)
769 | ls -la $?
770 | *
may be used in the target, prerequisites, or in the wildcard
function.
Danger: *
may not be directly used in a variable definitions
Danger: When *
matches no files, it is left as it is (unless run in the wildcard
function)
thing_wrong := *.o # Don't do this! '*' will not get expanded
774 | thing_right := $(wildcard *.o)
775 |
776 | all: one two three four
777 |
778 | # Fails, because $(thing_wrong) is the string "*.o"
779 | one: $(thing_wrong)
780 |
781 | # Stays as *.o if there are no files that match this pattern :(
782 | two: *.o
783 |
784 | # Works as you would expect! In this case, it does nothing.
785 | three: $(thing_right)
786 |
787 | # Same as rule three
788 | four: $(wildcard *.o)
789 | % Wildcard
790 |%
is really useful, but is somewhat confusing because of the variety of situations it can be used in.
-
792 |
- When used in "matching" mode, it matches one or more characters in a string. This match is called the stem. 793 |
- When used in "replacing" mode, it takes the stem that was matched and replaces that in a string. 794 |
%
is most often used in rule definitions and in some specific functions.
795 |
See these sections on examples of it being used:
797 |-
798 |
- Static Pattern Rules 799 |
- Pattern Rules 800 |
- String Substitution 801 |
- The vpath Directive 802 |
Automatic Variables
804 | 805 |There are many automatic variables, but often only a few show up:
806 |hey: one two
807 | # Outputs "hey", since this is the target name
808 | echo $@
809 |
810 | # Outputs all prerequisites newer than the target
811 | echo $?
812 |
813 | # Outputs all prerequisites
814 | echo $^
815 |
816 | # Outputs the first prerequisite
817 | echo $<
818 |
819 | touch hey
820 |
821 | one:
822 | touch one
823 |
824 | two:
825 | touch two
826 |
827 | clean:
828 | rm -f hey one two
829 |
830 | Fancy Rules
831 |Implicit Rules
832 | 833 |Make loves c compilation. And every time it expresses its love, things get confusing. Perhaps the most confusing part of Make is the magic/automatic rules that are made. Make calls these "implicit" rules. I don't personally agree with this design decision, and I don't recommend using them, but they're often used and are thus useful to know. Here's a list of implicit rules:
834 |-
835 |
- Compiling a C program:
n.o
is made automatically fromn.c
with a command of the form$(CC) -c $(CPPFLAGS) $(CFLAGS) $^ -o $@
836 | - Compiling a C++ program:
n.o
is made automatically fromn.cc
orn.cpp
with a command of the form$(CXX) -c $(CPPFLAGS) $(CXXFLAGS) $^ -o $@
837 | - Linking a single object file:
n
is made automatically fromn.o
by running the command$(CC) $(LDFLAGS) $^ $(LOADLIBES) $(LDLIBS) -o $@
838 |
The important variables used by implicit rules are:
840 |-
841 |
CC
: Program for compiling C programs; defaultcc
842 | CXX
: Program for compiling C++ programs; defaultg++
843 | CFLAGS
: Extra flags to give to the C compiler
844 | CXXFLAGS
: Extra flags to give to the C++ compiler
845 | CPPFLAGS
: Extra flags to give to the C preprocessor
846 | LDFLAGS
: Extra flags to give to compilers when they are supposed to invoke the linker
847 |
Let's see how we can now build a C program without ever explicitly telling Make how to do the compilation:
849 |CC = gcc # Flag for implicit rules
850 | CFLAGS = -g # Flag for implicit rules. Turn on debug info
851 |
852 | # Implicit rule #1: blah is built via the C linker implicit rule
853 | # Implicit rule #2: blah.o is built via the C compilation implicit rule, because blah.c exists
854 | blah: blah.o
855 |
856 | blah.c:
857 | echo "int main() { return 0; }" > blah.c
858 |
859 | clean:
860 | rm -f blah*
861 | Static Pattern Rules
862 | 863 |Static pattern rules are another way to write less in a Makefile. Here's their syntax:
864 |targets...: target-pattern: prereq-patterns ...
865 | commands
866 | The essence is that the given target
is matched by the target-pattern
(via a %
wildcard). Whatever was matched is called the stem. The stem is then substituted into the prereq-pattern
, to generate the target's prereqs.
A typical use case is to compile .c
files into .o
files. Here's the manual way:
objects = foo.o bar.o all.o
869 | all: $(objects)
870 | $(CC) $^ -o all
871 |
872 | foo.o: foo.c
873 | $(CC) -c foo.c -o foo.o
874 |
875 | bar.o: bar.c
876 | $(CC) -c bar.c -o bar.o
877 |
878 | all.o: all.c
879 | $(CC) -c all.c -o all.o
880 |
881 | all.c:
882 | echo "int main() { return 0; }" > all.c
883 |
884 | # Note: all.c does not use this rule because Make prioritizes more specific matches when there is more than one match.
885 | %.c:
886 | touch $@
887 |
888 | clean:
889 | rm -f *.c *.o all
890 | Here's the more efficient way, using a static pattern rule:
891 |objects = foo.o bar.o all.o
892 | all: $(objects)
893 | $(CC) $^ -o all
894 |
895 | # Syntax - targets ...: target-pattern: prereq-patterns ...
896 | # In the case of the first target, foo.o, the target-pattern matches foo.o and sets the "stem" to be "foo".
897 | # It then replaces the '%' in prereq-patterns with that stem
898 | $(objects): %.o: %.c
899 | $(CC) -c $^ -o $@
900 |
901 | all.c:
902 | echo "int main() { return 0; }" > all.c
903 |
904 | # Note: all.c does not use this rule because Make prioritizes more specific matches when there is more than one match.
905 | %.c:
906 | touch $@
907 |
908 | clean:
909 | rm -f *.c *.o all
910 | Static Pattern Rules and Filter
911 | 912 |While I introduce the filter function later on, it's common to use in static pattern rules, so I'll mention that here. The filter
function can be used in Static pattern rules to match the correct files. In this example, I made up the .raw
and .result
extensions.
obj_files = foo.result bar.o lose.o
914 | src_files = foo.raw bar.c lose.c
915 |
916 | all: $(obj_files)
917 | # Note: PHONY is important here. Without it, implicit rules will try to build the executable "all", since the prereqs are ".o" files.
918 | .PHONY: all
919 |
920 | # Ex 1: .o files depend on .c files. Though we don't actually make the .o file.
921 | $(filter %.o,$(obj_files)): %.o: %.c
922 | echo "target: $@ prereq: $<"
923 |
924 | # Ex 2: .result files depend on .raw files. Though we don't actually make the .result file.
925 | $(filter %.result,$(obj_files)): %.result: %.raw
926 | echo "target: $@ prereq: $<"
927 |
928 | %.c %.raw:
929 | touch $@
930 |
931 | clean:
932 | rm -f $(src_files)
933 | Pattern Rules
934 |Pattern rules are often used but quite confusing. You can look at them as two ways:
935 |-
936 |
- A way to define your own implicit rules 937 |
- A simpler form of static pattern rules 938 |
Let's start with an example first:
940 |# Define a pattern rule that compiles every .c file into a .o file
941 | %.o : %.c
942 | $(CC) -c $(CFLAGS) $(CPPFLAGS) $< -o $@
943 | Pattern rules contain a '%' in the target. This '%' matches any nonempty string, and the other characters match themselves. ‘%’ in a prerequisite of a pattern rule stands for the same stem that was matched by the ‘%’ in the target.
944 |Here's another example:
945 |# Define a pattern rule that has no pattern in the prerequisites.
946 | # This just creates empty .c files when needed.
947 | %.c:
948 | touch $@
949 | Double-Colon Rules
950 | 951 |Double-Colon Rules are rarely used, but allow multiple rules to be defined for the same target. If these were single colons, a warning would be printed and only the second set of commands would run.
952 |all: blah
953 |
954 | blah::
955 | echo "hello"
956 |
957 | blah::
958 | echo "hello again"
959 | Commands and execution
960 |Command Echoing/Silencing
961 | 962 |Add an @
before a command to stop it from being printed
You can also run make with -s
to add an @
before each line
all:
964 | @echo "This make line will not be printed"
965 | echo "But this will"
966 | Command Execution
967 | 968 |Each command is run in a new shell (or at least the effect is as such)
969 |all:
970 | cd ..
971 | # The cd above does not affect this line, because each command is effectively run in a new shell
972 | echo `pwd`
973 |
974 | # This cd command affects the next because they are on the same line
975 | cd ..;echo `pwd`
976 |
977 | # Same as above
978 | cd ..; \
979 | echo `pwd`
980 |
981 | Default Shell
982 | 983 |The default shell is /bin/sh
. You can change this by changing the variable SHELL:
SHELL=/bin/bash
985 |
986 | cool:
987 | echo "Hello from bash"
988 | Double dollar sign
989 |If you want a string to have a dollar sign, you can use $$
. This is how to use a shell variable in bash
or sh
.
Note the differences between Makefile variables and Shell variables in this next example.
991 |make_var = I am a make variable
992 | all:
993 | # Same as running "sh_var='I am a shell variable'; echo $sh_var" in the shell
994 | sh_var='I am a shell variable'; echo $$sh_var
995 |
996 | # Same as running "echo I am a make variable" in the shell
997 | echo $(make_var)
998 | Error handling with -k
, -i
, and -
999 |
1000 | Add -k
when running make to continue running even in the face of errors. Helpful if you want to see all the errors of Make at once.
Add a -
before a command to suppress the error
Add -i
to make to have this happen for every command.
one:
1003 | # This error will be printed but ignored, and make will continue to run
1004 | -false
1005 | touch one
1006 |
1007 | Interrupting or killing make
1008 | 1009 |Note only: If you ctrl+c
make, it will delete the newer targets it just made.
Recursive use of make
1011 | 1012 |To recursively call a makefile, use the special $(MAKE)
instead of make
because it will pass the make flags for you and won't itself be affected by them.
new_contents = "hello:\n\ttouch inside_file"
1014 | all:
1015 | mkdir -p subdir
1016 | printf $(new_contents) | sed -e 's/^ //' > subdir/makefile
1017 | cd subdir && $(MAKE)
1018 |
1019 | clean:
1020 | rm -rf subdir
1021 |
1022 | Export, environments, and recursive make
1023 | 1024 |When Make starts, it automatically creates Make variables out of all the environment variables that are set when it's executed.
1025 |# Run this with "export shell_env_var='I am an environment variable'; make"
1026 | all:
1027 | # Print out the Shell variable
1028 | echo $$shell_env_var
1029 |
1030 | # Print out the Make variable
1031 | echo $(shell_env_var)
1032 | The export
directive takes a variable and sets it the environment for all shell commands in all the recipes:
shell_env_var=Shell env var, created inside of Make
1034 | export shell_env_var
1035 | all:
1036 | echo $(shell_env_var)
1037 | echo $$shell_env_var
1038 | As such, when you run the make
command inside of make, you can use the export
directive to make it accessible to sub-make commands. In this example, cooly
is exported such that the makefile in subdir can use it.
new_contents = "hello:\n\techo \$$(cooly)"
1040 |
1041 | all:
1042 | mkdir -p subdir
1043 | printf $(new_contents) | sed -e 's/^ //' > subdir/makefile
1044 | @echo "---MAKEFILE CONTENTS---"
1045 | @cd subdir && cat makefile
1046 | @echo "---END MAKEFILE CONTENTS---"
1047 | cd subdir && $(MAKE)
1048 |
1049 | # Note that variables and exports. They are set/affected globally.
1050 | cooly = "The subdirectory can see me!"
1051 | export cooly
1052 | # This would nullify the line above: unexport cooly
1053 |
1054 | clean:
1055 | rm -rf subdir
1056 |
1057 | You need to export variables to have them run in the shell as well.
1058 |one=this will only work locally
1059 | export two=we can run subcommands with this
1060 |
1061 | all:
1062 | @echo $(one)
1063 | @echo $$one
1064 | @echo $(two)
1065 | @echo $$two
1066 |
1067 | .EXPORT_ALL_VARIABLES
exports all variables for you.
.EXPORT_ALL_VARIABLES:
1069 | new_contents = "hello:\n\techo \$$(cooly)"
1070 |
1071 | cooly = "The subdirectory can see me!"
1072 | # This would nullify the line above: unexport cooly
1073 |
1074 | all:
1075 | mkdir -p subdir
1076 | printf $(new_contents) | sed -e 's/^ //' > subdir/makefile
1077 | @echo "---MAKEFILE CONTENTS---"
1078 | @cd subdir && cat makefile
1079 | @echo "---END MAKEFILE CONTENTS---"
1080 | cd subdir && $(MAKE)
1081 |
1082 | clean:
1083 | rm -rf subdir
1084 | Arguments to make
1085 | 1086 | 1087 |There's a nice list of options that can be run from make. Check out --dry-run
, --touch
, --old-file
.
You can have multiple targets to make, i.e. make clean run test
runs the clean
goal, then run
, and then test
.
Variables Pt. 2
1090 |Flavors and modification
1091 | 1092 |There are two flavors of variables:
1093 |-
1094 |
- recursive (use
=
) - only looks for the variables when the command is used, not when it's defined.
1095 | - simply expanded (use
:=
) - like normal imperative programming -- only those defined so far get expanded
1096 |
# Recursive variable. This will print "later" below
1098 | one = one ${later_variable}
1099 | # Simply expanded variable. This will not print "later" below
1100 | two := two ${later_variable}
1101 |
1102 | later_variable = later
1103 |
1104 | all:
1105 | echo $(one)
1106 | echo $(two)
1107 | Simply expanded (using :=
) allows you to append to a variable. Recursive definitions will give an infinite loop error.
one = hello
1109 | # one gets defined as a simply expanded variable (:=) and thus can handle appending
1110 | one := ${one} there
1111 |
1112 | all:
1113 | echo $(one)
1114 | ?=
only sets variables if they have not yet been set
one = hello
1116 | one ?= will not be set
1117 | two ?= will be set
1118 |
1119 | all:
1120 | echo $(one)
1121 | echo $(two)
1122 | Spaces at the end of a line are not stripped, but those at the start are. To make a variable with a single space, use $(nullstring)
with_spaces = hello # with_spaces has many spaces after "hello"
1124 | after = $(with_spaces)there
1125 |
1126 | nullstring =
1127 | space = $(nullstring) # Make a variable with a single space.
1128 |
1129 | all:
1130 | echo "$(after)"
1131 | echo start"$(space)"end
1132 | An undefined variable is actually an empty string!
1133 |all:
1134 | # Undefined variables are just empty strings!
1135 | echo $(nowhere)
1136 | Use +=
to append
foo := start
1138 | foo += more
1139 |
1140 | all:
1141 | echo $(foo)
1142 | String Substitution is also a really common and useful way to modify variables. Also check out Text Functions and Filename Functions.
1143 |Command line arguments and override
1144 | 1145 |You can override variables that come from the command line by using override
.
1146 | Here we ran make with make option_one=hi
# Overrides command line arguments
1148 | override option_one = did_override
1149 | # Does not override command line arguments
1150 | option_two = not_override
1151 | all:
1152 | echo $(option_one)
1153 | echo $(option_two)
1154 | List of commands and define
1155 | 1156 |The define directive is not a function, though it may look that way. I've seen it used so infrequently that I won't go into details, but it's mainly used for defining canned recipes and also pairs well with the eval function.
1157 |define
/endef
simply creates a variable that is set to a list of commands. Note here that it's a bit different than having a semi-colon between commands, because each is run in a separate shell, as expected.
one = export blah="I was set!"; echo $$blah
1159 |
1160 | define two
1161 | export blah="I was set!"
1162 | echo $$blah
1163 | endef
1164 |
1165 | all:
1166 | @echo "This prints 'I was set'"
1167 | @$(one)
1168 | @echo "This does not print 'I was set' because each command runs in a separate shell"
1169 | @$(two)
1170 | Target-specific variables
1171 | 1172 |Variables can be set for specific targets
1173 |all: one = cool
1174 |
1175 | all:
1176 | echo one is defined: $(one)
1177 |
1178 | other:
1179 | echo one is nothing: $(one)
1180 | Pattern-specific variables
1181 | 1182 |You can set variables for specific target patterns
1183 |%.c: one = cool
1184 |
1185 | blah.c:
1186 | echo one is defined: $(one)
1187 |
1188 | other:
1189 | echo one is nothing: $(one)
1190 | Conditional part of Makefiles
1191 |Conditional if/else
1192 | 1193 |foo = ok
1194 |
1195 | all:
1196 | ifeq ($(foo), ok)
1197 | echo "foo equals ok"
1198 | else
1199 | echo "nope"
1200 | endif
1201 | Check if a variable is empty
1202 | 1203 |nullstring =
1204 | foo = $(nullstring) # end of line; there is a space here
1205 |
1206 | all:
1207 | ifeq ($(strip $(foo)),)
1208 | echo "foo is empty after being stripped"
1209 | endif
1210 | ifeq ($(nullstring),)
1211 | echo "nullstring doesn't even have spaces"
1212 | endif
1213 | Check if a variable is defined
1214 | 1215 |ifdef does not expand variable references; it just sees if something is defined at all
1216 |bar =
1217 | foo = $(bar)
1218 |
1219 | all:
1220 | ifdef foo
1221 | echo "foo is defined"
1222 | endif
1223 | ifndef bar
1224 | echo "but bar is not"
1225 | endif
1226 |
1227 | $(MAKEFLAGS)
1228 | 1229 |This example shows you how to test make flags with findstring
and MAKEFLAGS
. Run this example with make -i
to see it print out the echo statement.
all:
1231 | # Search for the "-i" flag. MAKEFLAGS is just a list of single characters, one per flag. So look for "i" in this case.
1232 | ifneq (,$(findstring i, $(MAKEFLAGS)))
1233 | echo "i was passed to MAKEFLAGS"
1234 | endif
1235 | Functions
1236 |First Functions
1237 | 1238 |Functions are mainly just for text processing. Call functions with $(fn, arguments)
or ${fn, arguments}
. Make has a decent amount of builtin functions.
bar := ${subst not,"totally", "I am not superman"}
1240 | all:
1241 | @echo $(bar)
1242 |
1243 | If you want to replace spaces or commas, use variables
1244 |comma := ,
1245 | empty:=
1246 | space := $(empty) $(empty)
1247 | foo := a b c
1248 | bar := $(subst $(space),$(comma),$(foo))
1249 |
1250 | all:
1251 | @echo $(bar)
1252 | Do NOT include spaces in the arguments after the first. That will be seen as part of the string.
1253 |comma := ,
1254 | empty:=
1255 | space := $(empty) $(empty)
1256 | foo := a b c
1257 | bar := $(subst $(space), $(comma) , $(foo)) # Watch out!
1258 |
1259 | all:
1260 | # Output is ", a , b , c". Notice the spaces introduced
1261 | @echo $(bar)
1262 |
1263 |
1266 |
1267 | String Substitution
1268 |$(patsubst pattern,replacement,text)
does the following:
"Finds whitespace-separated words in text that match pattern and replaces them with replacement. Here pattern may contain a ‘%’ which acts as a wildcard, matching any number of any characters within a word. If replacement also contains a ‘%’, the ‘%’ is replaced by the text that matched the ‘%’ in pattern. Only the first ‘%’ in the pattern and replacement is treated this way; any subsequent ‘%’ is unchanged." (GNU docs)
1270 |The substitution reference $(text:pattern=replacement)
is a shorthand for this.
There's another shorthand that replaces only suffixes: $(text:suffix=replacement)
. No %
wildcard is used here.
Note: don't add extra spaces for this shorthand. It will be seen as a search or replacement term.
1273 |foo := a.o b.o l.a c.o
1274 | one := $(patsubst %.o,%.c,$(foo))
1275 | # This is a shorthand for the above
1276 | two := $(foo:%.o=%.c)
1277 | # This is the suffix-only shorthand, and is also equivalent to the above.
1278 | three := $(foo:.o=.c)
1279 |
1280 | all:
1281 | echo $(one)
1282 | echo $(two)
1283 | echo $(three)
1284 | The foreach function
1285 | 1286 |The foreach function looks like this: $(foreach var,list,text)
. It converts one list of words (separated by spaces) to another. var
is set to each word in list, and text
is expanded for each word.
This appends an exclamation after each word:
foo := who are you
1288 | # For each "word" in foo, output that same word with an exclamation after
1289 | bar := $(foreach wrd,$(foo),$(wrd)!)
1290 |
1291 | all:
1292 | # Output is "who! are! you!"
1293 | @echo $(bar)
1294 | The if function
1295 | 1296 |if
checks if the first argument is nonempty. If so, runs the second argument, otherwise runs the third.
foo := $(if this-is-not-empty,then!,else!)
1298 | empty :=
1299 | bar := $(if $(empty),then!,else!)
1300 |
1301 | all:
1302 | @echo $(foo)
1303 | @echo $(bar)
1304 | The call function
1305 | 1306 |Make supports creating basic functions. You "define" the function just by creating a variable, but use the parameters $(0)
, $(1)
, etc. You then call the function with the special call
builtin function. The syntax is $(call variable,param,param)
. $(0)
is the variable, while $(1)
, $(2)
, etc. are the params.
sweet_new_fn = Variable Name: $(0) First: $(1) Second: $(2) Empty Variable: $(3)
1308 |
1309 | all:
1310 | # Outputs "Variable Name: sweet_new_fn First: go Second: tigers Empty Variable:"
1311 | @echo $(call sweet_new_fn, go, tigers)
1312 | The shell function
1313 | 1314 |shell - This calls the shell, but it replaces newlines with spaces!
1315 |all:
1316 | @echo $(shell ls -la) # Very ugly because the newlines are gone!
1317 | The filter function
1318 |The filter
function is used to select certain elements from a list that match a specific pattern. For example, this will select all elements in obj_files
that end with .o
.
obj_files = foo.result bar.o lose.o
1320 | filtered_files = $(filter %.o,$(obj_files))
1321 |
1322 | all:
1323 | @echo $(filtered_files)
1324 | Filter can also be used in more complex ways:
1325 |-
1326 |
Filtering multiple patterns: You can filter multiple patterns at once. For example,
1327 |$(filter %.c %.h, $(files))
will select all.c
and.h
files from the files list.
1328 | Negation: If you want to select all elements that do not match a pattern, you can use
1329 |filter-out
. For example,$(filter-out %.h, $(files))
will select all files that are not.h
files.
1330 | Nested filter: You can nest filter functions to apply multiple filters. For example,
1331 |$(filter %.o, $(filter-out test%, $(objects)))
will select all object files that end with.o
but don't start withtest
.
1332 |
Other Features
1334 |Include Makefiles
1335 |The include directive tells make to read one or more other makefiles. It's a line in the makefile that looks like this:
1336 |include filenames...
1337 | This is particularly useful when you use compiler flags like -M
that create Makefiles based on the source. For example, if some c files includes a header, that header will be added to a Makefile that's written by gcc. I talk about this more in the Makefile Cookbook
The vpath Directive
1339 | 1340 |Use vpath to specify where some set of prerequisites exist. The format is vpath <pattern> <directories, space/colon separated>
1341 | <pattern>
can have a %
, which matches any zero or more characters.
1342 | You can also do this globallyish with the variable VPATH
vpath %.h ../headers ../other-directory
1344 |
1345 | # Note: vpath allows blah.h to be found even though blah.h is never in the current directory
1346 | some_binary: ../headers blah.h
1347 | touch some_binary
1348 |
1349 | ../headers:
1350 | mkdir ../headers
1351 |
1352 | # We call the target blah.h instead of ../headers/blah.h, because that's the prereq that some_binary is looking for
1353 | # Typically, blah.h would already exist and you wouldn't need this.
1354 | blah.h:
1355 | touch ../headers/blah.h
1356 |
1357 | clean:
1358 | rm -rf ../headers
1359 | rm -f some_binary
1360 |
1361 | Multiline
1362 |The backslash ("\") character gives us the ability to use multiple lines when the commands are too long
1363 |some_file:
1364 | echo This line is too long, so \
1365 | it is broken up into multiple lines
1366 | .phony
1367 |Adding .PHONY
to a target will prevent Make from confusing the phony target with a file name. In this example, if the file clean
is created, make clean will still be run. Technically, I should have used it in every example with all
or clean
, but I wanted to keep the examples clean. Additionally, "phony" targets typically have names that are rarely file names, and in practice many people skip this.
some_file:
1369 | touch some_file
1370 | touch clean
1371 |
1372 | .PHONY: clean
1373 | clean:
1374 | rm -f some_file
1375 | rm -f clean
1376 | .delete_on_error
1377 | 1378 | 1379 |The make tool will stop running a rule (and will propogate back to prerequisites) if a command returns a nonzero exit status.DELETE_ON_ERROR
will delete the target of a rule if the rule fails in this manner. This will happen for all targets, not just the one it is before like PHONY. It's a good idea to always use this, even though make does not for historical reasons.
.DELETE_ON_ERROR:
1381 | all: one two
1382 |
1383 | one:
1384 | touch one
1385 | false
1386 |
1387 | two:
1388 | touch two
1389 | false
1390 | Makefile Cookbook
1391 |Let's go through a really juicy Make example that works well for medium sized projects.
1392 |The neat thing about this makefile is it automatically determines dependencies for you. All you have to do is put your C/C++ files in the src/
folder.
# Thanks to Job Vranish (https://spin.atomicobject.com/2016/08/26/makefile-c-projects/)
1394 | TARGET_EXEC := final_program
1395 |
1396 | BUILD_DIR := ./build
1397 | SRC_DIRS := ./src
1398 |
1399 | # Find all the C and C++ files we want to compile
1400 | # Note the single quotes around the * expressions. The shell will incorrectly expand these otherwise, but we want to send the * directly to the find command.
1401 | SRCS := $(shell find $(SRC_DIRS) -name '*.cpp' -or -name '*.c' -or -name '*.s')
1402 |
1403 | # Prepends BUILD_DIR and appends .o to every src file
1404 | # As an example, ./your_dir/hello.cpp turns into ./build/./your_dir/hello.cpp.o
1405 | OBJS := $(SRCS:%=$(BUILD_DIR)/%.o)
1406 |
1407 | # String substitution (suffix version without %).
1408 | # As an example, ./build/hello.cpp.o turns into ./build/hello.cpp.d
1409 | DEPS := $(OBJS:.o=.d)
1410 |
1411 | # Every folder in ./src will need to be passed to GCC so that it can find header files
1412 | INC_DIRS := $(shell find $(SRC_DIRS) -type d)
1413 | # Add a prefix to INC_DIRS. So moduleA would become -ImoduleA. GCC understands this -I flag
1414 | INC_FLAGS := $(addprefix -I,$(INC_DIRS))
1415 |
1416 | # The -MMD and -MP flags together generate Makefiles for us!
1417 | # These files will have .d instead of .o as the output.
1418 | CPPFLAGS := $(INC_FLAGS) -MMD -MP
1419 |
1420 | # The final build step.
1421 | $(BUILD_DIR)/$(TARGET_EXEC): $(OBJS)
1422 | $(CXX) $(OBJS) -o $@ $(LDFLAGS)
1423 |
1424 | # Build step for C source
1425 | $(BUILD_DIR)/%.c.o: %.c
1426 | mkdir -p $(dir $@)
1427 | $(CC) $(CPPFLAGS) $(CFLAGS) -c $< -o $@
1428 |
1429 | # Build step for C++ source
1430 | $(BUILD_DIR)/%.cpp.o: %.cpp
1431 | mkdir -p $(dir $@)
1432 | $(CXX) $(CPPFLAGS) $(CXXFLAGS) -c $< -o $@
1433 |
1434 |
1435 | .PHONY: clean
1436 | clean:
1437 | rm -r $(BUILD_DIR)
1438 |
1439 | # Include the .d makefiles. The - at the front suppresses the errors of missing
1440 | # Makefiles. Initially, all the .d files will be missing, and we don't want those
1441 | # errors to show up.
1442 | -include $(DEPS)
1443 |
1481 |
1482 |