In addition, any prerequisites that are themselves automatically generated should be updated first. In this example, edit depends on each of the eight object files; the object file main. A recipe may follow each line that contains a target and prerequisites. These recipes say how to update the target file.
A tab character or whatever character is specified by the. Bear in mind that make does not know anything about how the recipes work. It is up to you to supply recipes that will update the target file properly. All make does is execute the recipe you have specified when the target file needs to be updated.
Consequently, make never does anything with it unless you tell it specifically. If any of the commands generates an error, the building of the target is terminated and make exits. One file is considered newer than another if it has been modified more recently. It uses a flex scanner driven by a simple main:. When this makefile is executed for the first time, we see:. We now have an executable program.
Of course, real programs typically consist of more modules than this. Nevertheless, this is a functional and useful makefile. For instance, during the writing of this example, I executed the makefile several dozen times while experimenting with the program.
As you look at the makefile and sample execution, you may notice that the order in which commands are executed by make are nearly the opposite to the order they occur in the makefile. This top-down style is common in makefile s. Usually the most general form of target is specified first in the makefile and the details are left for later.
The make program supports this style in many ways. We will discuss these in great detail in later chapters. How did make decide what to do? The next prerequisite make considers is lexer. Again the chain of rules leads to lexer. Now that lexer. Finally, make examines -lfl. The -l option to gcc indicates a system library that must be linked into the application. GNU make includes special support for this syntax. When we run our program, we discover that aside from printing fees, fies, foes, and fums, it also prints text from the input file.
This is not what we want. The problem is that we have forgotten some rules in our lexical analyzer and flex is passing this unrecognized text to its output. While analyzing lexer. This, in turn, caused the update of lexer.
Now our word counting program is fixed:. All the project source code and the make description file are stored in a single directory. When make is invoked under these conditions, it automatically creates the first target it sees. To update a different target or to update more than one target include the target name on the command line:. When make is executed, it will read the description file and identify the target to be updated.
After the commands are run make assumes the target is up to date and moves on to the next target or exits. If the target you specify is already up to date, make will say so and immediately exit, doing nothing else:. If you specify a target that is not in the makefile and for which there is no implicit rule discussed in Chapter 2 , make will respond with:.
One of the most useful is --just-print or -n which tells make to display the commands it would execute for a particular target without actually executing them. This is particularly valuable while writing makefile s. It is also possible to set almost any makefile variable on the command line to override the default value or the value set in the makefile. Now that you have a basic understanding of make you can almost write your own makefile s.
Makefile s are usually structured top-down so that the most general target, often called all , is updated by default. More and more detailed targets follow with targets for program maintenance, such as a clean target to delete unwanted temporary files, coming last. As you can guess from these target names, targets do not have to be actual files, any name will do.
In the example above we saw a simplified form of a rule. The more complete but still not quite complete form of a rule is:. One or more targets appear to the left of the colon and zero or more prerequisites can appear to the right of the colon.
If no prerequisites are listed to the right, then only the target s that do not exist are updated. The set of commands executed to update a target are sometimes called the command script , but most often just the commands.
Each command must begin with a tab character. This obscure syntax tells make that the characters that follow the tab are to be passed to a subshell for execution. If you accidentally insert a tab as the first character of a noncommand line, make will interpret the following text as a command under most circumstances.
The comment character for make is the hash or pound sign,. All text from the pound sign to the end of line is ignored. Comments can be indented and leading whitespace is ignored.
The output will be:. This is called the target. The prerequisites or dependencies follow the target. For the sake of simplicity, we have not defined any prerequisites in this example. The command echo "Hello World" is called the recipe.
The recipe uses prerequisites to make a target. The target, prerequisites, and recipes together make a rule. As an example, a target might be a binary file that depends on prerequisites source files. On the other hand, a prerequisite can also be a target that depends on other dependencies:. It is not necessary for the target to be a file; it could be just a name for the recipe, as in our example.
We call these "phony targets. Going back to the example above, when make was executed, the entire command echo "Hello World" was displayed, followed by actual command output. We often don't want that. To suppress echoing the actual command, we need to start echo with :. Let's add a few more phony targets: generate and clean to the Makefile :. That's because only the first target in the makefile is the default target.
Often called the default goal , this is the reason you will see all as the first target in most projects. It is the responsibility of all to call other targets. We can override this behavior using a special phony target called. As the name suggests, the phony target. This is why most makefiles include all as a target that can call as many targets as needed.
Before running make , let's include another special phony target,. PHONY , where we define all the targets that are not files. Here is the complete makefile:. It is a good practice not to call clean in all or put it as the first target. Now that you have an idea of how a basic makefile works and how to write a simple makefile, let's look at some more advanced examples. Our latest Linux articles In the above example, most target and prerequisite values are hard-coded, but in real projects, these are replaced with variables and patterns.
For example, to assign the command gcc to a variable CC :. This is also called a recursive expanded variable , and it is used in a rule as shown below:. But if one tries to reassign a variable to itself, it will cause an infinite loop. Let's verify this:. We should have no problem running the makefile below:. The following makefile can compile all C programs by using variables, patterns, and functions. Let's explore it line by line:. In this case, all files with the.
In this case, if SRCS has values 'foo. Let's look at an example to understand this rule. Below is the rule in its expanded form:. Every prerequisite in the previous rule is considered a target for this rule. Below is the rewrite of the above makefile, assuming it is placed in the directory having a single file foo.
For more on makefiles, refer to the GNU Make manual , which offers a complete reference and examples. You can also read our Introduction to GNU Autotools to learn how to automate the generation of a makefile for your coding project. The filter function can be used in Static pattern rules to match the correct files. In this example, I made up the.
Perhaps the most confusing part of make is the magic rules and variables that are made. Here's a list of implicit rules:. 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. Add an before a command to stop it from being printed You can also run make with -s to add an before each line.
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. The export directive takes a variable and makes it accessible to sub-make commands. In this example, cooly is exported such that the makefile in subdir can use it. Note: export has the same syntax as sh, but they aren't related although similar in function.
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. Recursive definitions will give an infinite loop error. Spaces at the end of a line are not stripped, but those at the start are. String Substitution is also a really common and useful way to modify variables. Also check out Text Functions and Filename Functions.
You can override variables that come from the command line by using override. It has nothing to do with being a function. 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. Run this example with make -i to see it print out the echo statement.
Functions are mainly just for text processing. You can make your own using the call builtin function. Make has a decent amount of builtin functions. Note: don't add extra spaces for this shorthand. It will be seen as a search or replacement term.
It converts one list of words separated by spaces to another. This appends an exclamation after each word:. If so runs the second argument, otherwise runs the third. Make supports creating basic functions. You then call the function with the special call function. The include directive tells make to read one or more other makefiles. It's a line in the makefile makefile that looks like this:. 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. Use vpath to specify where some set of prerequisites exist. 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. The make tool will stop running a rule and will propogate back to prerequisites if a command returns a nonzero exit status. It's a good idea to always use this, even though make does not for historical reasons.
That is, it takes care of knowing what commands need to be executed in what order to take your software project from a collection of source files, object files, libraries, headers, etc. Suppose that you have a directory containing: tool tool. Check if either support. What a hassle! There is a lot to remember and several chances to make mistakes.
BTW-- the particulars of the command lines exhibited here depend on our software environment. These ones work on my computer. Of course, you could just run all three commands every time. That would work, but it doesn't scale well to a substantial piece of software like DOGS which takes more than 15 minutes to compile from the ground up on my MacBook. Which will perform the three steps shown above automatically.
The unindented lines here have the form "target: dependencies" and tell Make that the associated commands indented lines should be run if any of the dependencies are newer than the target. That is, the dependency lines describe the logic of what needs to be rebuilt to accommodate changes in various files.
If support. When support. The commands associated with each dependency line are set off with a tab see below should modify the target or at least touch it to update the modification time. At this point, our makefile is simply remembering the work that needs doing, but we still had to figure out and type each and every needed command in its entirety. It does not have to be that way: Make is a powerful language with variables, text manipulation functions, and a whole slew of built-in rules which can make this much easier for us.
GNU make supports a variety of functions for accessing information from the filesystem or other commands on the system. Implicit rules are built in, and a few will be discussed below. Pattern rules are specified in a form like. Make has a whole host of built-in rules that mean that very often, a project can be compile by a very simple makefile, indeed. The GNU make built in rule for C source files is the one exhibited above.
The built-in rules use a set of standard variables that allow you to specify local environment information like where to find the ROOT include files without re-writing all the rules. The ones most likely to be interesting to us are:. We have also added several standard targets that perform special actions like cleaning up the source directory.
Note that when make is invoked without an argument, it uses the first target found in the file in this case all , but you can also name the target to get which is what makes make clean remove the object files in this case. The input language for Make is whitespace sensitive. In particular, the action lines following dependencies must start with a tab. But a series of spaces can look the same and indeed there are editors that will silently convert tabs to spaces or vice versa , which results in a Make file that looks right and still doesn't work.
This was identified as a bug early on, but the story goes it was not fixed, because there were already 10 users. I've always thought this was easier to learn with a detailed example, so here's how I think of makefiles. For each section you have one line that's not indented and it shows the name of the section followed by dependencies.
The dependencies can be either other sections which will be run before the current section or files which if updated will cause the current section to be run again next time you run make. Here's a quick example keep in mind that I'm using 4 spaces where I should be using a tab, Stack Overflow won't let me use tabs :.
When you type make , it will choose the first section a3driver. Assuming it has or has never been run , it will compile a3driver. The reason I showed the first example is that it shows the power of makefiles. If you need to compile another file, you can just add another section.
Here's an example with a secondFile. This way if you change something in secondFile. Or alternately, if you change something in a3driver. It's also traditional to include a section named "all" and a section named "clean".
I think the only difference is changing the -o a3driver to -o a3driver. Why does everyone like to list out source files? A simple find command can take care of that easily. Just drop it in a directory containing. C files and then type make I used friedmud's answer. I looked into this for a while, and it seems to be a good way to get started. This solution also has a well defined method of adding compiler flags. More working examples are the best teacher, sometimes. Makefiles seem to be very complex.
This configuration solved that problem. The latter suggestion is slightly better since it reuses GNU Make implicit rules. However, in order to work, a source file must have the same name as the final executable i. Notice, it is not necessary to declare sources. Intermediate object files are generated using implicit rule. We modify LINK. For example:. The attentive reader will notice that this Makefile does not rebuild properly if one header is changed.
Add these lines to fix the problem:. The second line just uses them. For sure, a well written Makefile should also include clean and distclean rules:. The all rule is also appreciated. In order to work, it should be the first rule of your file:. The user can set it to install your program at an alternative system mandatory for cross-compilation process.
One final word: Do not place source files in sub-directories. If you really want to do that, keep this Makefile in the root directory and use full paths to identify your files i. Your Make file will have one or two dependency rules depending on whether you compile and link with a single command, or with one command for the compile and one for the link.
Dependency are a tree of rules that look like this note that the indent must be a TAB :. There must be a blank line after the commands for a target, and there must not be a blank line before the commands. The first target in the makefile is the overall goal, and other targets are built only if the first target depends on them. Stack Overflow for Teams — Collaborate and share knowledge with a private group.
Create a free Team What is Teams? Collectives on Stack Overflow. Learn more. Asked 11 years, 4 months ago. Active 1 year, 4 months ago. Viewed k times. That's it. Everything else is contained with the. Improve this question. Peter Mortensen It turns out these are special constants that communicate to make how we want to compile the files hellomake.
By putting the object files--hellomake. Using this form of makefile is sufficient for most small scale projects. However, there is one thing missing: dependency on the include files. If you were to make a change to hellomake. In order to fix this, we need to tell make that all. We can do this by writing a simple rule and adding it to the makefile. This addition first creates the macro DEPS, which is the set of. Then we define a rule that applies to all files ending in the.
The rule says that the. The rule then says that to generate the. In the example below, all of the include files should be listed as part of the macro DEPS, and all of the object files should be listed as part of the macro OBJ. So what if we want to start putting our. Also, can we somehow hide those annoying. The answer, of course, is yes. The following makefile defines paths to the include and lib directories, and places the object files in an obj subdirectory within the src directory.
It also has a macro defined for any libraries you want to include, such as the math library -lm. This makefile should be located in the src directory. Note that it also includes a rule for cleaning up your source and object directories if you type make clean.
See Splitting Long Lines. To use this makefile to delete the executable file and all the object files from the directory, type:. When a target is a file, it needs to be recompiled or relinked if any of its prerequisites change. In addition, any prerequisites that are themselves automatically generated should be updated first.
In this example, edit depends on each of the eight object files; the object file main. A recipe may follow each line that contains a target and prerequisites. These recipes say how to update the target file. A tab character or whatever character is specified by the. Bear in mind that make does not know anything about how the recipes work. Some code editors like Microsoft Visual Studio have their own built in build tools.
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:. 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.
The following Makefile has three separate rules. When you run make blah in the terminal, it will build a program called blah in a series of steps:. It will first look at its list of dependencies , and if any of them are older, it will first run the targets for those dependencies, and then run itself.
The second time this is run, neither target will run because both targets exist. I suggest that you always wrap it in the wildcard function, because otherwise you may fall into a common pitfall described below. It's oddly unhelpful and I find it more confusing than useful. There are many automatic variables , but often only a few show up:. Make loves c compilation. And every time it expresses its love, things get confusing. Here's the syntax for a new type of rule called a static pattern:.
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. Here's the manual way :. While I introduce functions later on, I'll forshadow what you can do with them. The filter function can be used in Static pattern rules to match the correct files. In this example, I made up the. Perhaps the most confusing part of make is the magic rules and variables that are made. Here's a list of implicit rules:.
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. Add an before a command to stop it from being printed You can also run make with -s to add an before each line.
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. The export directive takes a variable and makes it accessible to sub-make commands. In this example, cooly is exported such that the makefile in subdir can use it.
Note: export has the same syntax as sh, but they aren't related although similar in function. 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. Recursive definitions will give an infinite loop error.