Search code, repositories, users, issues, pull requests...

Provide feedback.

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly.

To see all available qualifiers, see our documentation .

  • Notifications

⚙️📕 A guide to Makefiles!

michaelfromyeg/makefiles

  • Shell 100.0%

make file wiki

Getting Started

Why do makefiles exist, what alternatives are there to make, the versions and types of make, running the examples, makefile syntax, the essence of make, more quick examples, the all target, multiple targets, automatic variables and wildcards, automatic variables, fancy rules, implicit rules, static pattern rules, static pattern rules and filter, pattern rules, double-colon rules, commands and execution, command echoing/silencing, command execution, default shell, double dollar sign.

  • Error handling with -k, -i, and -

Interrupting or killing make

Recursive use of make, export, environments, and recursive make, arguments to make, variables pt. 2, flavors and modification, command line arguments and override, list of commands and define, target-specific variables, pattern-specific variables, conditional part of makefiles, conditional if/else, check if a variable is empty, check if a variable is defined, $(makeflags), first functions, string substitution, the foreach function, the if function, the call function, the shell function, other features, include makefiles, the vpath directive, .delete_on_error, makefile cookbook.

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.

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.

Good luck, and I hope you are able to slay the confusing world of Makefiles!

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.

Here's an example dependency graph that you might build with Make. If any file's dependencies changes, then the file will get recompiled:

make file wiki

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.

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.

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.

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:

Note: Makefiles must be indented using TABs and not spaces or make will fail.

Here is the output of running the above example:

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.

A Makefile consists of a set of rules . A rule generally looks like this:

  • The targets are file names, separated by spaces. Typically, there is only one per rule.
  • The commands are a series of steps typically used to make the target(s). These need to start with a tab character , not spaces.
  • 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

Let's start with a hello world example:

There's already a lot to take in here. Let's break it down:

  • We have one target called hello
  • This target has two commands
  • This target has no prerequisites

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:

Then create the Makefile (called Makefile , as always):

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:

When we run make again, the following set of steps happens:

  • The first target is selected, because the first target is the default target
  • This has a prerequisite of blah.c
  • Make decides if it should run the blah target. It will only run if blah doesn't exist, or blah.c is newer than blah

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 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.

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.

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:

  • Make selects the target blah , because the first target is the default target
  • blah requires blah.o , so make searches for the blah.o target
  • blah.o requires blah.c , so make searches for the blah.c target
  • blah.c has no dependencies, so the echo command is run
  • The cc -c command is then run, because all of the blah.o dependencies are finished
  • The top cc command is run, because all the blah dependencies are finished
  • That's it: blah is a compiled c program

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.

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:

  • 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
  • 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

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:

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:

Reference variables using either ${} or $()

Making multiple targets and you want all of them to run? Make an all target. Since this is the first rule listed, it will run by default if make is called without specifying a target.

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.

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.

* 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)

% is really useful, but is somewhat confusing because of the variety of situations it can be used in.

  • When used in "matching" mode, it matches one or more characters in a string. This match is called the stem.
  • When used in "replacing" mode, it takes the stem that was matched and replaces that in a string.
  • % is most often used in rule definitions and in some specific functions.

See these sections on examples of it being used:

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. 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:

  • Compiling a C program: n.o is made automatically from n.c with a command of the form $(CC) -c $(CPPFLAGS) $(CFLAGS) $^ -o $@
  • Compiling a C++ program: n.o is made automatically from n.cc or n.cpp with a command of the form $(CXX) -c $(CPPFLAGS) $(CXXFLAGS) $^ -o $@
  • Linking a single object file: n is made automatically from n.o by running the command $(CC) $(LDFLAGS) $^ $(LOADLIBES) $(LDLIBS) -o $@

The important variables used by implicit rules are:

  • CC : Program for compiling C programs; default cc
  • CXX : Program for compiling C++ programs; default g++
  • CFLAGS : Extra flags to give to the C compiler
  • CXXFLAGS : Extra flags to give to the C++ compiler
  • CPPFLAGS : Extra flags to give to the C preprocessor
  • LDFLAGS : Extra flags to give to compilers when they are supposed to invoke the linker

Let's see how we can now build a C program without ever explicitly telling Make how to do the compililation:

Static pattern rules are another way to write less in a Makefile, but I'd say are more useful and a bit less "magic". Here's their syntax:

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 :

Here's the more efficient way , using a static pattern rule:

While I introduce functions later on, I'll foreshadow 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 .raw and .result extensions.

Pattern rules are often used but quite confusing. You can look at them as two ways:

  • A way to define your own implicit rules
  • A simpler form of static pattern rules

Let's start with an example first:

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.

Here's another example:

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

Each command is run in a new shell (or at least the effect is as such)

The default shell is /bin/sh . You can change this by changing the variable SHELL:

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.

Error handling with -k , -i , and -

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.

Note only: If you ctrl+c make, it will delete the newer targets it just made.

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.

When Make starts, it automatically creates Make variables out of all the environment variables that are set when it's executed.

The export directive takes a variable and sets it the environment for all shell commands in all the recipes:

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.

You need to export variables to have them run in the shell as well.

.EXPORT_ALL_VARIABLES exports all variables for you.

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 .

There are two flavors of variables:

  • recursive (use = ) - only looks for the variables when the command is used , not when it's defined .
  • simply expanded (use := ) - like normal imperative programming -- only those defined so far get expanded

Simply expanded (using := ) allows you to append to a variable. Recursive definitions will give an infinite loop error.

?= only sets variables if they have not yet been set

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)

An undefined variable is actually an empty string!

Use += to append

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 . Here we ran make with make option_one=hi

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 .

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.

Variables can be set for specific targets

You can set variables for specific target patterns

ifdef does not expand variable references; it just sees if something is defined at all

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.

Functions are mainly just for text processing. Call functions with $(fn, arguments) or ${fn, arguments} . Make has a decent amount of builtin functions .

If you want to replace spaces or commas, use variables

Do NOT include spaces in the arguments after the first. That will be seen as part of the string.

$(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 )

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.

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:

if checks if the first argument is nonempty. If so, runs the second argument, otherwise runs the third.

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.

shell - This calls the shell, but it replaces newlines with spaces!

The include directive tells make to read one or more other makefiles. It's a line in the 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. The format is vpath <pattern> <directories, space/colon separated> <pattern> can have a % , which matches any zero or more characters. You can also do this globallyish with the variable VPATH

The backslash ("\") character gives us the ability to use multiple lines when the commands are too long

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 didn't to keep the examples clean. Additionally, "phony" targets typically have names that are rarely file names, and in practice many people skip this.

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.

Let's go through a really juicy Make example that works well for medium sized projects.

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.

make is a utility for building applications. This tutorial will teach you how to use this utility with Makefiles. This tutorial is primarily focused on GNU make.

You may think of Make as merely a tool for building large binaries or libraries (and it is, almost to a fault), but it’s much more than that. Makefiles are machine-readable documentation that make your workflow reproducible. – Mike Bostock , "Why Use Make" [1]

Hand compilation [ edit | edit source ]

Before we start talking about "make", let's first describe the build process used long ago: "hand compilation", aka "manual build". That processes isn't too bad if you only have one or two source files. A simple compilation process would be by typing the following code by hand:

For beginners, this might take a while to get used to. As an alternative, using make the command would be:

Both commands will do the same thing - take the file.cpp source file, compile it and then link it into an executable.

But where the problem comes in is where the user has to use more than one source file, or is dependent on libraries. Making an SDL application might consist of something like this:

This is getting harder to remember, isn't it?

Let's add some optimisation:

Do you really want to type that whole command line every time you make the tiniest edit to your source files? This is where make comes in - it will save your time!

Basics [ edit | edit source ]

A make file works as a simple dependency tree - it compiles the stuff that is outdated and then links your software together. You will have to specify the compilation options, but they will not be as tough on you anymore. A simple makefile for compiling your application:

To compile your application, you may do:

Well, you may now ask, how much of use is this? I can make a shell script for this myself! So lets now work on multiple files and object files - your application is big enough to be linked now: it contains five files.

The Test Case [ edit | edit source ]

Globally, there are three functions present:

File2 and file3 have their header files, so they could be inter-linked. The actual application will look like this:

So, how would I link this all up? Well, the most basic way is to do it all by hand:

However, make would offer a simpler way, Makefile :

Pretty different, eh? There's a different approach to do this, which is what makes make so good:

How easy is it to expand now? Just add a file to the OBJS list and you're done!

This is a complete makefile that handles the complete process of converting several source files (and creating a bunch of ".o" files as an intermediate step) into the final "file1" executable.

Good programmers put human-readable comments (lines starting with the "#" character) in the makefile to describe why the makefile was written and what make is intended to do with this makefile (which, alas, is not always what actually happens).

Advanced make [ edit | edit source ]

Long lines [ edit | edit source ].

Some statements in a makefile can be very long. To make them easier to read, some programmers break up long statements into several shorter, easier-to-read physical lines. Many consoles displayed 80 characters across, which is the threshold some programmers use for breaking up lines and comments.

In short, a programmer may decide it looks nicer to writes several short physical lines that together compose one statement, like this:

Rather than the same statement, crammed into a single physical line:

Make Clean [ edit | edit source ]

When you type "make clean" from the command prompt, "make" deletes all the files that you specified were easily replaceable files—i.e., the intermediate and output files generated from your irreplaceable hand-written source files.

To tell "make" that some file is an easily replaceable file, add it to the "rm" line of the "clean" section of your makefile, and that file will be deleted *every* time you type "make clean" at the command prompt. (If you don't already have a "clean" section in your makefile, add a section to the end of your makefile that looks like the following):

In this example, we've told "make" that all intermediate object files ("*.o") and the final executable ("file") are safe-to-delete, easily regenerated files. Typically people (or automake scripts) set up the clean step to delete every target in the makefile. [2]

Typically a programmer periodically runs "make clean", then archives *every* file in the directory, and then runs "make" to regenerate every file. Then he tests the program executable, confident that the program he is testing can be easily regenerated entirely from the files in the archive.

Variables [ edit | edit source ]

"make" accepts three ways of setting variables.

  • Recursively expanded variables are defined by using variable = value . This means if one variable 'y' contains references to another variable 'x', and 'x' changes after the 'y' being defined, 'y' will include the change made to 'x'.
  • Simply expanded variables are defined by using variable := value . This means if one variable 'x' contains references to another variable 'y', the 'y' variable will be scanned for once and for all.
  • If you just want to make sure a variable is set, you can use variable ?= value . If the variable is already set, then the definition will not be run; if not, then 'variable' will be set as 'value'. [3]

File Names With Special Characters [ edit | edit source ]

Many programmers recommend not creating files with spaces or dollar signs in them, in order to avoid the 'spaces in file names' error in "make" and many other utilities. [4]

If you must deal with a file that has spaces or dollar signs in the file name (such as the file "my $0.02 program.c"), sometimes you can escape the literal name of the file with double slashes and double dollar signs—in the Makefile, that filename can be represented as "my\\ $$0.02\\ program.c". [5]

Alas, the double-slash escape doesn't work when "make" works with lists of files (which are internally represented as space-separated filenames). One work-around is to refer to that file name using a space-free representation like "my+$$0.02+program.c", then later in the make file use the $(subst) function to convert that space-free representation back to the actual on-disk file name. [4] Alas, this work-around can't handle filenames that include both spaces and plus-signs.

Perhaps it's simplest to avoid filenames with spaces in them as inputs or outputs of "make".

Name of the makefile [ edit | edit source ]

When creating a new makefile, give it the literal name " Makefile " (8 characters, no extension).

In principle, you could create a makefile with some other name, such as makefile or GNUmakefile , which (like Makefile ) are automatically found by the GNU version of the make utility, or some other name that you pass to the make utility with the --file option. [6]

Example makefiles [ edit | edit source ]

References [ edit | edit source ].

  • ↑ Mike Bostock "Why Use Make" . 2013.
  • ↑ "Makefiles and RMarkdown" . 2015.
  • ↑ "GNU Make Manual" section "6.2 The Two Flavors of Variables".
  • ↑ a b John Graham-Cumming. "GNU Make meets file names with spaces in them" . CM Crossroads 2007.
  • ↑ John Graham-Cumming. "GNU Make escaping: a walk on the wild side" CM Crossroads 2007.
  • ↑ "GNU Make Manual" section "3.2 What Name to Give Your Makefile".

Further reading [ edit | edit source ]

Books and manuals [ edit | edit source ].

  • GNU Make documentation
  • FreeBSD make manual page
  • Microsoft NMAKE reference
  • GNU make Standard Library .
  • Managing Projects with GNU make .

Tutorials [ edit | edit source ]

  • The GNU C Programming Tutorial - Writing a makefile
  • Makefile Tutorial: How To Write A Makefile
  • OPUS Makefile Tutorial
  • Makefile Tutorial for C, gcc, & gmake
  • Using NMake

Articles [ edit | edit source ]

  • "Ask Mr. Make" series of article about GNU Make
  • What is wrong with make?
  • What’s Wrong With GNU make?
  • Peter Miller. "Recursive Make Considered Harmful" . (was Recursive Make Considered Harmful )
  • Advanced Auto-Dependency Generation .
  • "Kleknev: a coarse-grained profiler for build systems" . Sometimes "make" is used to build extremely large, complicated systems; the Kleknev system helps people figure out what items are eating the most time during that build process.

make file wiki

  • Shelf:Utility software
  • Shelf:Open source software
  • Alphabetical/M
  • Subject:Utility software
  • Subject:Utility software/all books
  • Subject:Computer software/all books
  • Subject:Computing/all books
  • Subject:Books by subject/all books
  • Subject:Open source software
  • Subject:Open source software/all books
  • Book:Wikibooks Stacks/Books
  • Shelf:Utility software/all books
  • Shelf:Computer software/all books
  • Department:Computing/all books
  • Shelf:Open source software/all books
  • Freshly started books
  • Books by completion status/all books

Navigation menu

What is a Makefile and how does it work?

Open Data Policy

Opensource.com

If you want to run or update a task when certain files are updated, the make utility can come in handy. The make utility requires a file, Makefile (or makefile ), which defines set of tasks to be executed. You may have used make to compile a program from source code. Most open source projects use make to compile a final executable binary, which can then be installed using make install .

In this article, we'll explore make and Makefile using basic and advanced examples. Before you start, ensure that make is installed in your system.

Basic examples

Let's start by printing the classic "Hello World" on the terminal. Create a empty directory myproject containing a file Makefile with this content:

Now run the file by typing make inside the directory myproject . The output will be:

In the example above, say_hello behaves like a function name, as in any programming language. 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 .

To summarize, below is the syntax of a typical 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 @ :

Now try to run make again. The output should display only this:

Let's add a few more phony targets: generate and clean to the Makefile :

If we try to run make after the changes, only the target say_hello will be executed. 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 .DEFAULT_GOAL .

Let's include that at the beginning of our makefile:

This will run the target generate as the default:

As the name suggests, the phony target .DEFAULT_GOAL can run only one target at a time. This is why most makefiles include all as a target that can call as many targets as needed.

Let's include the phony target all and remove .DEFAULT_GOAL :

Before running make , let's include another special phony target, .PHONY , where we define all the targets that are not files. make will run its recipe regardless of whether a file with that name exists or what its last modification time is. Here is the complete makefile:

The make should call say_hello and generate :

It is a good practice not to call clean in all or put it as the first target. clean should be called manually when cleaning is needed as a first argument to make :

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.

Advanced examples

More Linux resources

  • Linux commands cheat sheet
  • Advanced Linux commands cheat sheet
  • Free online course: RHEL Technical Overview
  • Linux networking cheat sheet
  • SELinux cheat sheet
  • Linux common commands cheat sheet
  • What are Linux containers?
  • 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.

The simplest way to define a variable in a makefile is to use the = operator. 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:

As you may have guessed, the recipe expands as below when it is passed to the terminal:

Both ${CC} and $(CC) are valid references to call gcc . But if one tries to reassign a variable to itself, it will cause an infinite loop. Let's verify this:

Running make will result in:

To avoid this scenario, we can use the := operator (this is also called the simply expanded variable ). We should have no problem running the makefile below:

Patterns and functions

The following makefile can compile all C programs by using variables, patterns, and functions. Let's explore it line by line:

Lines starting with # are comments.

Line .PHONY = all clean defines phony targets all and clean .

Variable LINKERFLAG defines flags to be used with gcc in a recipe.

SRCS := $(wildcard *.c) : $(wildcard pattern) is one of the functions for filenames . In this case, all files with the .c extension will be stored in a variable SRCS .

BINS := $(SRCS:%.c=%) : This is called as substitution reference . In this case, if SRCS has values 'foo.c bar.c' , BINS will have 'foo bar' .

Line all: ${BINS} : The phony target all calls values in ${BINS} as individual targets.

Let's look at an example to understand this rule. Suppose foo is one of the values in ${BINS} . Then % will match foo ( % can match any target name). Below is the rule in its expanded form:

As shown, % is replaced by foo . $< is replaced by foo.o . $< is patterned to match prerequisites and $@ matches the target. This rule will be called for every value in ${BINS}

Every prerequisite in the previous rule is considered a target for this rule. Below is the rule in its expanded form:

Finally, we remove all binaries and object files in target clean .

Below is the rewrite of the above makefile, assuming it is placed in the directory having a single file foo.c:

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.

psachin

Related Content

GNOME

A Makefile is a file which controls the 'make' command. Make is available on virtually every platform, and is used to control the build process of a project. Once a Makefile has been written for a project, make can easily and efficiently build your project and create the required output file(s).

Make reads dependency information from your Makefile, figures out which output files need (re-)building (because they are either missing or older than their corresponding input files), executes the necessary commands to actually do the (re-)building. This compares favourably to "build batchfiles" that always rebuild the whole project.

In doing this, make is not limited to any specific set of languages. Any tool that takes some input file and generates an output file can be controlled via make.

A Makefile can offer several different "targets", which can be invoked by 'make <target>'. A frequently-used target is 'make clean', which removes any temporary files, or 'make install', which installs the project in its target location - but you can also give a specific output file as a target, and have make process only that file. Invoking make without a target parameter builds the default target (which is usually to build the whole project).

But 'make' requires a well-written Makefile to do these things efficiently and reliably.

Makefile tutorial

The 'make' manual will tell you about the hundreds of things you can do with a Makefile, but it doesn't give you an example for a good Makefile. The following examples are mostly shaped after the real-life PDCLib Makefile I used at the time, and shows some of the "tricks" used therein that may not be that obvious to the make beginner.

The Makefile creates only one project-wide linker library, but it should be easy to expand it for multiple binaries/libraries.

(Note: There are several different flavours of make around, and POSIX defines a common denominator for them. This tutorial specifically targets GNU make. See the discussion page for further info.)

It is best practice to name your Makefile Makefile (without an extension), because when make is executed without any parameters, it will by default look for that file in the current directory. It also makes the file show up prominently on top of directory listings, at least on Unix machines.

Generally speaking, a Makefile consists of definitions and rules .

A definition declares a variable, and assigns a value to it. Its general syntax is VARIABLE := Value .

Note: Frequently, you will see definitions using "=" instead of ":=". Such a definition will result in the assignment being evaluated every time the variable is used , while ":=" evaluates only once at the startup of make, which is usually what you want. Don't go changing other people's Makefiles, though - ":=" is a GNU extension to the make syntax.

A rule defines a target , 0..n dependencies , and 0..n commands . The general idea is that make checks if the target (file) is there; if it isn't, or any of the dependencies is newer than the target, the commands are executed. The general syntax is:

Both dependency and command are optional. There might be more than one command line, in which case they are executed in sequence.

Note that commands must be tab-indented . If your editor environment is set to replace tabs with spaces, you have to undo that setting while editing a Makefile.

What makes Makefiles so hard to read, for the beginner, is that it is not procedural in syntax (i.e., executed top-down), but functional: 'make' reads the whole Makefile, building a dependency tree, and then resolves the dependencies by hopping from rule to rule as necessary until the target you gave it on the command line has successfully been resolved.

But let's not go into internal details of 'make'. This is a tutorial, not a man page, so it will show you how a real-life Makefile could be built, and the ideas behind each line.

Automated Testing

As the Makefile presented in this tutorial takes care of automated testing in a special way, this approach will be explained up front, so the related parts of the tutorial will make sense to you.

As stated above, this tutorial is mainly derived from work done on the PDCLib project - which builds a single linker library. In that project, there is strictly one library function per source file. In each such source file, there is a test driver attached for conditional compilation, like this:

Thus, when that source is compiled with gcc -c , it results in an object file with the library function code; when compiled with gcc -DTEST , it gives a test driver executable for that function. Returning the number of errors allows to do a grand total of errors encountered (see below).

First, various "file lists" are assembled which are needed later in the Makefile.

Non-Source Files

Further down we will have a target "dist" , which packages all required files into a tarball for distribution. Lists of the sources and headers are created anyway. But there are commonly some auxiliary files, which are not referenced anywhere else in the Makefile but should still end up in the tarball. These are listed here.

Project Directories

Those are subdirectories holding the actual sources. (Or rather, searched for source files automatically, see below.) These could be subprojects, or whatever. We could simply search for source files starting with the current working directory, but if you like to have temporary subdirectories in your project (for testing, keeping reference sources etc.), that wouldn't work.

Note that this is not a recursive approach; there is no Makefile in those subdirectories. Dependencies are hard enough to get right if you use one Makefile. At the bottom of this article is a link to a very good paper on the subject titled "recursive make considered harmful"; not only is a single Makefile easier to maintain (once you learned a couple of tricks), it can also be more efficient!

Sources and Headers

It should be obvious to see what these two lines do. We now have a list of all source and header files in our project directories.

Object Files and Test Driver Executables

OBJFILES should be clear - a list of the source files, with *.c exchanged for *.o . TSTFILES does the same for the filename suffix *_t , which we will use for our test driver executables.

Dependencies, pt. 1

Many people edit their Makefile every time they add/change an #include somewhere in their code. (Or forget to do so, resulting in some scratching of heads.)

But most compilers - including GCC - can do this automatically for you! Although the approach looks a little backward. For each source file, GCC will create a dependency file (which is canonically made to end in *.d ), which contains a Makefile dependency rule listing that source file's includes. (And more, but see below.)

We need two seperate sets of dependency files; one for the library objects, and one for the test driver executables (which usually have additional includes, and thus dependencies, not needed for the OBJFILES).

Distribution Files

The last list is the one with all sources, headers, and auxiliary files that should end up in a distribution tarball.

The next one can take you by surprise. When you write a rule for make clean , and there happens to be a file named clean in your working directory, you might be surprised to find that make does nothing, because the "target" of the rule clean already exists. To avoid this, declare such rules as phony , i.e. disable the checking for a file of that name. These will be executed every time:

If you thought -Wall does tell you everything, you'll be in for a rude surprise now. If you don't even use -Wall , shame on you. ;)

It is suggested to add new warning options to your project one at a time instead of all at once, to avoid getting swamped in warnings. ;) These flags are merely recommendations for C work. If you use C++, you need different ones. Check out the GCC manual; each major compiler update changes the list of available warning options.

Now come the rules, in their typical backward manner (top-level rule first). The topmost rule is the default one (if 'make' is called without an explicit target). It is common practice to have the first rule called "all".

Top-Level Targets

The @ at the beginning of a line tells make to be quiet, i.e. not to echo the executed commands on the console prior to executing them. The Unix credo is "no news is good news". You don't get a list of processed files with cp or tar , either, so it's completely beyond me why developers chose to have their Makefiles churn out endless lists of useless garbage. One very practical advantage of shutting up make is that you actually get to see those compiler warnings, instead of having them drowned out by noise.

The - at the beginning of a line tells make to continue even in case an error is encountered (default behaviour is to terminate the whole build).

The $(RM) in the clean rule is the platform-independent command to remove a file.

The $? in the pdclib.a rule is an internal variable, which make expands to list all dependencies to the rule which are newer than the target .

Automated Testing, pt. 2

Call it crude, but it works beautifully for me. The leading - means that 'make' will not abort when encountering an error, but continue with the loop.

The echo " TST $$file" in there is useful in case you get a SEGFAULT or something like that from one of your test drivers. (Without echoing the drivers as they are executed, you would be at a loss as to which one crashed.)

Dependencies, pt. 2

Further below, you will see how dependency files are generated . Here, we include all of them, i.e. make the dependencies listed in them part of our Makefile. Never mind that they might not even exist when we run our Makefile the first time - the leading "-" again suppresses the errors.

Extracting TODO Statements

Taking all files in your project, with exception of the Makefile itself, this will grep all those TODO and FIXME comments from your files, and display them in the terminal. It is nice to be remembered of what is still missing before you do a release. To add another keyword, just insert another -e keyword .

Dependencies, pt. 3

Now comes the dependency magic I talked about earlier. Note that this needs GCC 3.3 or newer.

Isn't it a beauty? ;-)

The -MMD flag generates the dependency file (%.d), which will hold (in Makefile syntax) rules making the generated file (%.o in this case) depend on the source file and any non-system headers it includes . That means the object file gets recreated automatically whenever relevant sources are touched. If you want to also depend on system headers (i.e., checking them for updates on each compile), use -MD instead. The -MP option adds empty dummy rules, which avoid errors should header files be removed from the filesystem.

Compiling the object file actually looks like a side effect. ;-)

Note that the dependency list of the rule includes the Makefile itself. If you changed e.g. the CFLAGS in the Makefile, you want them to be applied, don't you? Using the $< macro ("first dependency") in the command makes sure we do not attempt to compile the Makefile as C source.

Of course we also need a rule for generating the test driver executables (and their dependency files):

Here you can see why test driver executables get a *_t suffix instead of a *.t extension: The -MMD option uses the basename (i.e., filename without extension) of the compiled file as basis for the dependency file. If we would compile the sources into abc.o and abc.t , the dependency files would both be named abc.d , overwriting each other.

Other compilers differ a bit in their support for this, so look up their specifics when using something else than GCC .

Backing up your files is a perfect candidate of a task that should be automated. However, this is generally achieved through a version control system .

Below is an example of a backup target, which creates a dated 7-Zip archive of the directory where the Makefile resides.

A well-written Makefile can make maintaining a code base much easier, as it can wrap complex command sequences into simple 'make' invocations. Especially for large projects, it also cuts back on compilation times when compared to a dumb "build.sh" script. And, once written, modifications to a well-written Makefile are seldom necessary.

Advanced Techniques

Some of the stuff we did above already was pretty advanced, and no mistake. But we needed those features for the basic yet convenient setup. Below you will find some even trickier stuff, which might not be for everybody but is immensely helpful if you need it.

Conditional Evaluation

Sometimes it is useful to react on the existence or content of certain environment variables. For example, you might have to rely on the path to a certain framework being passed in FRAMEWORK_PATH. Perhaps the error message given by the compiler in case the variable is not set is not helpful, or it takes long until 'make' gets to the point where it actually detects the error. You want to fail early, and with a meaningful error message.

Luckily, 'make' allows for conditional evaluation and manual error reporting, quite akin to the C preprocessor:

Multi-Target

Preliminary work has been done to write an improved Makefile, which allows generating multiple binaries with individual settings while still being easy to configure and use. While this is not yet in "tutorial" format, commented source can be found here .

  • User:Solar/Makefile , A more complex example capable of building multiple executables and libraries from a single Makefile.

External Links

  • JAWS , a pre-configured CMake setup which, while not geared toward OS development, is a definite step forward from "naked" Makefiles.
  • Recursive Make Considered Harmful by Peter Miller A paper detailing why the traditional approach of recursive make invocations harms performance and reliability.
  • Implementing non-recursive make by Emile van Bergen Further input on the subject of non-recursive, low-maintenance Makefile creation.
  • Manual for GNU make
  • Managing Projects with GNU Make , the O'Reilly book on GNU Make
  • Level 1 Tutorials
  • Build Tools

Personal tools

  • View source
  • View history
  • OS Projects
  • Random page
  • Editing help
  • Recent changes
  • What links here
  • Related changes
  • Special pages
  • Printable version
  • Permanent link

In other languages

  • This page was last modified on 9 July 2023, at 12:54.
  • This page has been accessed 131,236 times.
  • Privacy policy
  • About OSDev Wiki
  • Disclaimers

Powered by MediaWiki

Stack Exchange Network

Stack Exchange network consists of 183 Q&A communities including Stack Overflow , the largest, most trusted online community for developers to learn, share their knowledge, and build their careers.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

What is a makefile exactly and how we can create one?

I know this is a silly question, but since I am trying so hard to learn linux by myself, I need some help from you fellows.

I found this task on the internet and I am trying to solve it but I don't understand exactly how can I use makefiles in linux and how can I create them.

Let's suppose my print working directory is /home/george/Documents

I want to create a makefile which does the following:

  • Displays a message as follows "hello work, today is Sun". Sun comes from Sunday. So I must use date command in this make file to display just first three letters.

compress /etc/hosts in /tmp using gzip (probably here should be something like

enzotib's user avatar

  • Makefiles are there to selectively build outdated object files from source files, in a software development activity. It has nothing to do to what you would do. –  enzotib Aug 17, 2013 at 14:21

3 Answers 3

to answer your question I cant give you a one line / paragraph answer because it deals with every thing.Read the first link it have everything you need with examples too.

Good tutorial that can explain everything about make

  • http://mrbook.org/tutorials/make/
  • http://manpages.ubuntu.com/manpages/raring/man1/create_makefile.1.html
  • http://manpages.ubuntu.com/manpages/raring/man1/make.1.html

Raja G's user avatar

  • 3 the first link should be : mrbook.org/blog/tutorials/make –  Shahryar Saljoughi Aug 11, 2017 at 6:35
  • mrbook.org/blog/tutorials/make tutorial uses outdated c++ code and no longer compiles. See this question to understand and fix. –  David Mar 3, 2018 at 11:16
  • Links are dead . –  ComputerScientist May 13, 2019 at 15:59

A Makefile is used as a "map" for C programs compilation. They work with the make utility, an describe how a program has to be compiled/linked in order to work correctly once turned into a executable file. For global UNIX/shell tasks, you're looking for shell scripts, not makefiles :)

See http://en.wikipedia.org/wiki/Make_(software)#Makefiles for more information about makefiles, and http://en.wikipedia.org/wiki/Shell_script to discover shell scripts.

A basic shell script for what you're trying to do could be :

Store this in a file, and execute it using your shell prompt ( bash myscript.sh , sh myscript.sh , ...). You can also make the script executable using :

And then execute it with your default interpretor with :

John WH Smith's user avatar

  • 1 I am trying to create a makefile which does this not a shell script. –  Adrian George Aug 17, 2013 at 14:27
  • Then you have to develop a C program which does this, and compile it using a Makefile, if you want. Makefiles do not execute Linux tasks, they guide C programs compilation, it is a completely different thing. –  John WH Smith Aug 17, 2013 at 14:30
  • 1 @JohnWHSmith There is nothing special about compiling C programs. Makefiles can be used to perform a variety of tasks. (With that said, many tasks are poorly suited for the use of makefiles.) –  Eliah Kagan Aug 17, 2013 at 15:06

Why not create a shell script, then create a symbolic link that points to the shell script you created? Place the symbolic link in a directory that's in the PATH, so that you can 'run' the symbolic link no matter the directory in which you are located.

user544202's user avatar

You must log in to answer this question.

Not the answer you're looking for browse other questions tagged makefile ..

  • The Overflow Blog
  • Controlling cloud costs: Where to start, and where to go from there sponsored post
  • Will antitrust suits benefit developers?
  • Featured on Meta
  • New Focus Styles & Updated Styling for Button Groups
  • Upcoming initiatives on Stack Overflow and across the Stack Exchange network
  • AI-generated content is not permitted on Ask Ubuntu

Hot Network Questions

  • My guitar's high e string keeps snapping at the tuning peg, i think my tuning peg is the problem
  • Alternative to passing chord harmonization in closed position
  • Employer has changed start date after I’ve already signed contract and issued back to them (UK)
  • How do I set up bitcoin.conf in Bitcoin Knots' to stop spam and low value transactions?
  • Global character of ABC/Szpiro inequalities
  • Which is more important to linear modelling: Normality or Adjusted R-Squared?
  • Are light rays always bent in any gravitational field, or just in a strong one like a black hole?
  • Is Bellman backup unbiased?
  • recreate a figure with TikZ from an entrance exam
  • Is it possible to have very different sea levels?
  • "Here Document" as a Single Line Command?
  • Would strengthening Foundation and Choice in NBG, make it equi-consistent with MK?
  • Get equations aligned
  • drive slowly or drive more slowly?
  • German equivalent titles which use continous conjugration of verb
  • In "Southpaw“, why didn't they do gunpowder residue (GSR) tests on everybody in the hallway?
  • Possible grammar error in textbook by National Geographic?
  • Is the (surprising) applicability of mathematics to the physical world a brute fact or something crying out for a (theistic) explanation?
  • What were the most common software distribution formats for MacOS Classic?
  • Is it legal for someone to forge my signature with my knowledge and approval?
  • Is this lesser version of Life Transference balanced?
  • Nuclear attack followed by a ground invasion
  • Rockstar Poetic Number Literals!
  • First order filters in Direct Form I (RBJ Cookbook)

make file wiki

Make (software)

Unix utility for build automation / from wikipedia, the free encyclopedia, dear wikiwand ai, let's keep it short by simply answering these key questions:.

Can you list the top facts and stats about Make (software)?

Summarize this article for a 10 year old

In software development , Make is a build automation tool that builds executable programs and libraries from source code by reading files called makefiles which specify how to derive the target program. Though integrated development environments and language -specific compiler features can also be used to manage a build process, Make remains widely used, especially in Unix and Unix-like operating systems .

Make is not limited to building programs. It can also be used to manage any project where some files need to be updated automatically from other files whenever the other files change.

Make is one of the most widespread dependency-tracking build utilities, primarily due to its early inclusion in Unix , starting with PWB/UNIX 1.0, which featured a variety of tools for software development tasks. [1] It was created by Stuart Feldman in April 1976 at Bell Labs . [2] [3] [1] Feldman received the 2003 ACM Software System Award for authoring the tool. [4]

Feldman was inspired to write Make by the experience of a coworker in futilely debugging a program of his where the executable was accidentally not being updated with changes:

Make originated with a visit from Steve Johnson (author of yacc, etc.), storming into my office, cursing the Fates that had caused him to waste a morning debugging a correct program (bug had been fixed, file hadn't been compiled, cc *.o was therefore unaffected). As I had spent a part of the previous evening coping with the same disaster on a project I was working on, the idea of a tool to solve it came up. It began with an elaborate idea of a dependency analyzer, boiled down to something much simpler, and turned into Make that weekend. Use of tools that were still wet was part of the culture. Makefiles were text files, not magically encoded binaries, because that was the Unix ethos : printable, debuggable, understandable stuff. —   Stuart Feldman, The Art of Unix Programming , Eric S. Raymond 2003

Before Make's introduction, the Unix build system most commonly consisted of operating system dependent "make" and "install" shell scripts accompanying their program's source code. Being able to combine the commands for the build targets into a single file and being able to abstract dependency tracking and archive handling was an important step in the direction of modern build environments.

Derivatives

Make has been rewritten numerous times, including new implementations that use the same file format and basic algorithmic principles and also provide non-standard enhancements. Examples are:

  • Sun DevPro Make appeared in 1986 with SunOS-3.2. With SunOS-3.2, It was delivered as an optional program; with SunOS-4.0, SunPro Make was made the default Make program. [5] [ better   source   needed ] In December 2006, Sun DevPro Make was made open source as part of the efforts to open-source Solaris . [6] [7]
  • dmake or Distributed Make that came with Sun Solaris Studio as its default Make, but not the default one on the Solaris Operating System (SunOS). It was originally required to build OpenOffice, but in 2009 [8] the build system was rewritten to use GNU Make. While Apache OpenOffice still contains a mixture of both build systems, [9] the much more actively developed LibreOffice only uses the modernized "gbuild" now. [8]
  • BSD Make ( pmake , [10] bmake [11] or fmake [12] ), which is derived from Adam de Boor's work on a version of Make capable of building targets in parallel , and survives with varying degrees of modification in FreeBSD , [11] NetBSD [13] and OpenBSD . [14] Distinctively, it has conditionals and iterative loops which are applied at the parsing stage and may be used to conditionally and programmatically construct the makefile, [15] including generation of targets at runtime. [ citation needed ]
  • GNU Make (short gmake ) is the standard implementation of Make for Linux and macOS. [16] It provides several extensions over the original Make, such as conditionals. It also provides many built-in functions which can be used to eliminate the need for shell-scripting in the makefile rules as well as to manipulate the variables set and used in the makefile. [17] For example, the foreach function can be used to iterate over a list of values, such as the names of files in a given directory. [18] GNU Make is required for building many software systems, including GNU Compiler Collection (GCC) (since version 3.4 [19] ), the Linux kernel, [20] [21] Apache OpenOffice, [9] LibreOffice, [8] and Mozilla Firefox . [22]
  • Rocky Bernstein's Remake [23] is a fork of GNU Make and provides several extensions over GNU Make, such as better location and error-location reporting, execution tracing, execution profiling, and it contains a debugger.
  • Glenn Fowler's nmake [24] is unrelated to the Microsoft program of the same name. Its input is similar to Make, but not compatible. This program provides shortcuts and built-in features, which according to its developers reduces the size of makefiles by a factor of 10.
  • Microsoft nmake , a command-line tool which normally is part of Visual Studio . [25] It supports preprocessor directives such as includes and conditional expressions which use variables set on the command-line or within the makefiles. [26] [27] Inference rules differ from Make; for example they can include search paths. [28] The Make tool supplied with Embarcadero products has a command-line option that "Causes MAKE to mimic Microsoft's NMAKE.". [29] Qt Project 's Jom tool is a clone of nmake. [30]
  • Mk replaced Make in Research Unix , starting from version 9. [31] A redesign of the original tool by Bell Labs programmer Andrew G. Hume, it features a different syntax. Mk became the standard build tool in Plan 9 , Bell Labs' intended successor to Unix. [32]
  • Kati is Google's replacement of GNU Make, as of 2020 used in Android OS builds. It translates the makefile into ninja for faster incremental builds (similar to the cmake metatool). [33]
  • Snakemake is a python-driven implementation for compiling and running bioinformatics workflows. [34]

POSIX includes standardization of the basic features and operation of the Make utility, and is implemented with varying degrees of compatibility with Unix-based versions of Make. In general, simple makefiles may be used between various versions of Make with reasonable success. GNU Make, Makepp and some versions of BSD Make default to looking first for files named "GNUmakefile", [35] "Makeppfile" [36] and "BSDmakefile" [37] respectively, which allows one to put makefiles which use implementation-defined behavior in separate locations.

Make is traditionally used for compiling source code files (e.g. *.c, *.ts files, etc.) to a target object file type that can be directly executed either as a standalone executable (as is the case for C source code ), or not (as is the case for TypeScript source code ).

Make is not limited to object files only: It is applicable in any use case where a set of files is dependent on the content of another set of files. Make includes a dependency mechanism to manage these relations correctly. A possible use case not related to programming is to detect a change made to an image file (the source) and then convert the file to some specific format, copy the result into a content management system, and send e-mail to a set of users indicating that the actions were performed.

Make is invoked with a list of target names in form of command-line arguments :

Without arguments, Make builds the first target that appears in its makefile, which is traditionally a symbolic "phony" target named all which doesn't correspond to any stored file.

Make decides whether a target needs to be regenerated by comparing file modification times. [38] This solves the problem of avoiding the building of files which are already up to date, but it fails when a file changes but its modification time stays in the past. Such changes could be caused by restoring an older version of a source file, or when a network filesystem is a source of files and its clock or time zone is not synchronized with the machine running Make. The user must handle this situation by forcing a complete build. Conversely, if a source file's modification time is in the future, it triggers unnecessary rebuilding, which may inconvenience users.

Makefiles are also traditionally used for providing commands to automate common software development tasks. One such makefile is called from the command line:

The makefile language is similar to declarative programming . [40] [41] [42] [43] This class of language, in which necessary end conditions are described but the order in which actions are to be taken is not important, is sometimes confusing to programmers used to imperative programming .

A common problem in build automation is the tailoring of a build process to a given platform . For example, the compiler used on one platform might not accept the same options as the one used on another. This problem is typically handled by generating platform-specific build instructions, which in turn are processed by Make. Common tools for this process are Autoconf , CMake or GYP (or more advanced NG ).

Makefiles may contain five types of constructs: [44]

  • An explicit rule says when and how to remake one or more files, called the rule's targets. It lists the other files that the targets depend on, called the prerequisites of the target, and may also give a recipe to use to create or update the targets.
  • An implicit rule says when and how to remake a class of files based on their names. It describes how a target may depend on a file with a name similar to the target and gives a recipe to create or update such a target.
  • A variable definition is a line that specifies a text string value for a variable that can be substituted into the text later.
  • A directive is an instruction for make to do something special while reading the makefile such as reading another makefile.
  • Lines starting with # are used for comments .

A makefile consists of rules . Each rule begins with a textual dependency line which defines a target followed by a colon (:) and optionally an enumeration of components (files or other targets) on which the target depends. The dependency line is arranged so that the target (left hand of the colon) depends on components (right hand of the colon). It is common to refer to components as prerequisites of the target. [45]

Usually each rule has a single unique target, rather than multiple targets.

For example, a C .o object file is created from .c files, so .c files come first (i.e. specific object file target depends on a C source file and header files ). Because Make itself does not understand, recognize or distinguish different kinds of files, this opens up a possibility for human error.

Each dependency line may be followed by a series of TAB indented command lines which define how to transform the components (usually source files) into the target (usually the "output"). If any of the prerequisites has a more recent modification time than the target, the command lines are run. The GNU Make documentation refers to the commands associated with a rule as a "recipe".

The first command may appear on the same line after the prerequisites, separated by a semicolon,

for example,

Make can decide where to start through topological sorting .

Each command line must begin with a tab character to be recognized as a command. The tab is a whitespace character, but the space character does not have the same special meaning. This is problematic, since there may be no visual difference between a tab and a series of space characters. This aspect of the syntax of makefiles is often subject to criticism; it has been described by Eric S. Raymond as "one of the worst design botches in the history of Unix" [46] and The Unix-Haters Handbook said "using tabs as part of the syntax is like one of those pungee stick traps in The Green Berets ". Feldman explains the choice as caused by a workaround for an early implementation difficulty preserved by a desire for backward compatibility with the very first users:

Why the tab in column 1? Yacc was new, Lex was brand new. I hadn't tried either, so I figured this would be a good excuse to learn. After getting myself snarled up with my first stab at Lex, I just did something simple with the pattern newline-tab. It worked, it stayed. And then a few weeks later I had a user population of about a dozen, most of them friends, and I didn't want to screw up my embedded base. The rest, sadly, is history. —   Stuart Feldman [46]

GNU Make. since version 3.82, allows the choice of any symbol (one character) as the recipe prefix using the .RECIPEPREFIX special variable, for example:

Each command is executed by a separate shell or command-line interpreter instance. Since operating systems use different command-line interpreters this can lead to unportable makefiles. For example, GNU Make (all POSIX Makes) executes commands with /bin/sh by default, where Unix commands like cp are normally used. In contrast to that, Microsoft's nmake executes commands with cmd.exe where batch commands like copy are available but not necessarily cp.

A rule may omit the recipe. The dependency line can consist solely of components that refer to other targets, for example:

The command lines of a rule are usually arranged so that they generate the target. An example: if file.html is newer, it is converted to text. The contents of the makefile:

The rule above would be triggered when Make updates "file.txt". In the following invocation, Make would typically use this rule to update the "file.txt" target if "file.html" were newer.

Command lines can have one or more of the following three prefixes:

  • a hyphen-minus (-), specifying that errors are ignored
  • an at sign (@), specifying that the command is not printed to standard output before it is executed
  • a plus sign (+), the command is executed even if Make is invoked in a "do not execute" mode

Ignoring errors and silencing echo can alternatively be obtained via the special targets .IGNORE and .SILENT . [47]

Microsoft's NMAKE has predefined rules that can be omitted from these makefiles, e.g. c.obj $( CC )$( CFLAGS ) .

A makefile can contain definitions of macros. Macros are usually referred to as variables when they hold simple string definitions, like CC = clang . Macros in makefiles may be overridden in the command-line arguments passed to the Make utility. Environment variables are also available as macros.

Macros allow users to specify the programs invoked and other custom behavior during the build process. For example, the macro CC is frequently used in makefiles to refer to the location of a C compiler, and the user may wish to specify a particular compiler to use.

New macros (or simple "variables") are traditionally defined using capital letters:

A macro is used by expanding it. Traditionally this is done by enclosing its name inside $() . (Omitting the parentheses leads to Make interpreting the next letter after the $ as the entire variable name.) An equivalent form uses curly braces rather than parentheses, i.e. ${} , which is the style used in the BSDs .

Macros can be composed of shell commands by using the command substitution operator, denoted by backticks ( ` ).

The content of the definition is stored "as is". Lazy evaluation is used, meaning that macros are normally expanded only when their expansions are actually required, such as when used in the command lines of a rule. An extended example:

The generic syntax for overriding macros on the command line is:

Makefiles can access any of a number of predefined internal macros , with ? and @ being the most common.

A somewhat common syntax expansion is the use of += , ?= , and != instead of the equal sign. It works on BSD and GNU makes alike. [48]

Suffix rules

Suffix rules have "targets" with names in the form .FROM.TO and are used to launch actions based on file extension. In the command lines of suffix rules, POSIX specifies [49] that the internal macro $< refers to the first prerequisite and $@ refers to the target. In this example, which converts any HTML file into text, the shell redirection token > is part of the command line whereas $< is a macro referring to the HTML file:

When called from the command line, the example above expands.

Pattern rules

Suffix rules cannot have any prerequisites of their own. [50] If they have any, they are treated as normal files with unusual names, not as suffix rules. GNU Make supports suffix rules for compatibility with old makefiles but otherwise encourages usage of pattern rules . [51]

A pattern rule looks like an ordinary rule, except that its target contains exactly one % character within the string. The target is considered a pattern for matching file names: the % can match any substring of zero or more characters, [52] while other characters match only themselves. The prerequisites likewise use % to show how their names relate to the target name.

The example above of a suffix rule would look like the following pattern rule:

Other elements

Single-line comments are started with the hash symbol (#).

Some directives in makefiles can include other makefiles.

Line continuation is indicated with a backslash \ character at the end of a line.

Example makefiles

The makefile:

Below is a very simple makefile that by default (the "all" rule is listed first) compiles a source file called "helloworld.c" using the system's C compiler and also provides a "clean" target to remove the generated files if the user desires to start over. The $@ and $< are two of the so-called internal macros (also known as automatic variables) and stand for the target name and "implicit" source, respectively. In the example below, $^ expands to a space delimited list of the prerequisites. There are a number of other internal macros. [49] [53]

Many systems come with predefined Make rules and macros to specify common tasks such as compilation based on file suffix. This lets users omit the actual (often unportable) instructions of how to generate the target from the source(s). On such a system the makefile above could be modified as follows:

That "helloworld.o" depends on "helloworld.c" is now automatically handled by Make. In such a simple example as the one illustrated here this hardly matters, but the real power of suffix rules becomes evident when the number of source files in a software project starts to grow. One only has to write a rule for the linking step and declare the object files as prerequisites. Make will then implicitly determine how to make all the object files and look for changes in all the source files.

Simple suffix rules work well as long as the source files do not depend on each other and on other files such as header files. Another route to simplify the build process is to use so-called pattern matching rules that can be combined with compiler-assisted dependency generation. As a final example requiring the gcc compiler and GNU Make, here is a generic makefile that compiles all C files in a folder to the corresponding object files and then links them to the final executable. Before compilation takes place, dependencies are gathered in makefile-friendly format into a hidden file ".depend" that is then included to the makefile. Portable programs ought to avoid constructs used below.

Dependency tracking

Makefile consist of dependencies and a forgotten or an extra one may not be immediately obvious to the user and may result in subtle bugs in the generated software that are hard to catch. Various approaches may be used to avoid this problem and keep dependencies in source and makefiles in sync. One approach is by using compiler to keep track of dependencies changes .e.g GCC can statically analyze the source code and produce rules for the given file automatically by using -MM switch. The other approach would be makefiles or third-party tools that would generate makefiles with dependencies (e.g. Automake toolchain by the GNU Project , can do so automatically).

Another approach is to use meta-build tools like CMake , Meson etc.

  • List of build automation software
  • Dependency graph
  • [2] "V7/usr/src/cmd/make/ident.c" . tuhs.org . 1 September 2013. Archived from the original on 1 September 2013 . Retrieved 18 March 2018 .
  • [3] Feldman, S. I. (April 1979). "Make --- A Program for Maintaining Computer Programs". Software: Practice and Experience . 9 (4): 255–265. CiteSeerX   10.1.1.39.7058 . doi : 10.1002/spe.4380090402 . S2CID   33059412 .
  • [4] Matthew Doar (2005). Practical Development Environments . O'Reilly Media . p.   94. ISBN   978-0-596-00796-6 .
  • [5] "Google Groups" . arquivo.pt . Archived from the original on 22 January 2011 . Retrieved 18 March 2018 . {{ cite web }} : CS1 maint: bot: original URL status unknown ( link )
  • [6] "OpenSolaris at Two (Jim Grisanzio)" . 12 December 2013. Archived from the original on 12 December 2013 . Retrieved 18 March 2018 .
  • [7] Grisanzio, Jim. The OpenSolaris Story .
  • [8] "Development/Gbuild - The Document Foundation Wiki" . wiki.documentfoundation.org . Retrieved 18 March 2018 .
  • [9] "Apache OpenOffice Building Guide - Apache OpenOffice Wiki" . wiki.openoffice.org . Retrieved 18 March 2018 .
  • [10] FreeBSD 2.0.5 Make Source Code , 1993
  • [11] "Bmake(1)" .
  • [12] https://manpages.debian.org/jessie/freebsd-buildutils/fmake.1 [ bare URL plain text file ]
  • [13] "make" . NetBSD Manual Pages . Retrieved 9 July 2020 .
  • [14] "make(1) - OpenBSD manual pages" . man.openbsd.org . Retrieved 18 March 2018 .
  • [15] "make" . FreeBSD . Retrieved 9 July 2020 . Makefile inclusion, conditional structures and for loops reminiscent of the C programming language are provided in make.
  • [16] Arnold Robbins (2005), Unix in a Nutshell, Fourth Edition , O'Reilly
  • [17] "8. Functions for Transforming Text" , GNU make , Free Software Foundation, 2013
  • [18] "8.5 The foreach Function" , GNU make , Free Software Foundation, 2013
  • [19] "GCC 3.4 Release Series Changes, New Features, and Fixes" . Free Software Foundation. 2006.
  • [20] Javier Martinez Canillas (December 26, 2012). "Kbuild: the Linux Kernel Build System" . Linux Journal .
  • [21] Greg Kroah-Hartman (2006), Linux Kernel in a Nutshell , O'Reilly
  • [22] "Build Instructions" .
  • [23] Rocky Bernstein. "Remake – GNU Make with comprehensible tracing and a debugger" .
  • [24] Glenn Fowler (January 4, 2012). "nmake Overview" . Information and Software Systems Research, AT&T Labs Research. Archived from the original on September 2, 2015 . Retrieved May 26, 2014 .
  • [25] "NMAKE Reference Visual Studio 2015" . Microsoft. 2015.
  • [26] "Makefile Preprocessing Directives" . 2014.
  • [27] "Makefile Preprocessing Operators" . Microsoft. 2014.
  • [28] "Search Paths in Rules" . Microsoft. 2014.
  • [29] "MAKE" . CodeGear(TM). 2008.
  • [30] "Jom - Qt Wiki" . Qt Project. 2021.
  • [31] McIlroy, M. D. (1987). A Research Unix reader: annotated excerpts from the Programmer's Manual, 1971–1986 (PDF) (Technical report). Bell Labs. CSTR 139.
  • [32] Hume, Andrew G.; Flandrena, Bob (2002). "Maintaining files on Plan 9 with Mk" . Plan 9 Programmer’s Manual . AT&T Bell Laboratories. Archived from the original on July 11, 2015.
  • [33] "google/kati: An experimental GNU make clone" . GitHub . 30 November 2020.
  • [34] Mölder, Felix; Jablonski, Kim Philipp; Letcher, Brice; Hall, Michael B.; Tomkins-Tinch, Christopher H.; Sochat, Vanessa; Forster, Jan; Lee, Soohyun; Twardziok, Sven O.; Kanitz, Alexander; Wilm, Andreas (2021-04-19). "Sustainable data analysis with Snakemake" . F1000Research . 10 : 33. doi : 10.12688/f1000research.29032.2 . ISSN   2046-1402 . PMC   8114187 . PMID   34035898 .
  • [35] "GNU 'make' " . Free Software Foundation.
  • [36] "Makepp" .
  • [37] "Free BSD make" .
  • [38] How to sort Linux ls command file output Archived September 13, 2016, at the Wayback Machine
  • [39] "makefile" . Apple Developer Documentation: Uniform Type Identifiers . Apple Inc .
  • [40] Adams, P. and Solomon, M., 1993, An overview of the CAPITL software development environment. In International Workshop on Software Configuration Management (pp. 1-34). Berlin, Heidelberg: Springer Berlin Heidelberg.
  • [41] an overview on dsls Archived October 23, 2007, at the Wayback Machine , 2007/02/27, phoenix wiki
  • [42] Re: Choreography and REST Archived September 12, 2016, at the Wayback Machine , from Christopher B Ferris on 2002-08-09
  • [43] Target Junior Makefiles Archived January 7, 2010, at the Wayback Machine , Andrew W. Fitzgibbon and William A. Hoffman
  • [44] 3.1 What Makefiles Contain , GNU make , Free Software Foundation
  • [45] "Prerequisite Types (GNU make)" . GNU.org . GNU Project . Retrieved 15 December 2020 .
  • [46] "Chapter 15. Tools: make: Automating Your Recipes", The Art of Unix Programming , Eric S. Raymond 2003
  • [47] make   –   Shell and Utilities Reference, The Single UNIX Specification , Version 4 from The Open Group
  • [48] make(1)   –   FreeBSD General Commands Manual
  • [49] "make" . www.opengroup.org . Retrieved 18 March 2018 .
  • [50] "GNU make manual: suffix rules" . Free Software Foundation.
  • [51] "GNU make manual: pattern rules" . Free Software Foundation.
  • [52] See section Pattern Matching Rules in the SunPro man page Archived May 29, 2014, at the Wayback Machine
  • [53] Automatic Variables Archived April 25, 2016, at the Wayback Machine GNU `make'

External links

  • GNU Make homepage

Breder.org logo

The Basics of GNU Make

A quick guide on getting started with the GNU Make tool and using Makefiles to specify build targets and build dependencies. The make command is commonly used in Linux/Unix environments for building programs from source, but can also be applied for building derivate documents.

GNU Make is a tool intended for building executables from its binary and source dependencies.

More concretely, you specify the dependency tree between generated and source files on a Makefile, and GNU Make takes care of rebuilding the needed files as needed, when their sources are modified.

It also allow you to group shell commands with a more friendly name. For example, instead of having a directory full of shell scripts, you can have a single Makefile and call the same shell commands through, for example, make clean .

Makefile format

A Makefile is simply a text file named Makefile and placed in the root of your project. When the make command is called, it will look for it and act as instructed.

A Makefile is composed of targets, dependencies and shell commands, as shown below:

The target is either a friendly label or the path to an specific path of a file which is built through the commands listed below. The dependencies are other targets which should be built first, that is, targets which the present target depends upon.

When the make command is called without arguments, the first target is built. When it is called make [target] , the particular target is built (and all of its dependencies, as needed).

Using variables in Makefiles

A variable may be specified as follows:

It can then be referred in recipes as follows:

Using result of shell command

You can use a special $(shell ...) function to use the value of the output of the shell command. For example:

This will generate a file such as notes-2022-03-28.md , running the shell command date --iso to get today's date in the ISO format (YYYY-MM-DD).

Automatic variables

  • $@ name of the target of the rule.
  • $? name of all prerequisites newer than the target.
  • $^ name of all prerequisites of the target.
  • $< name of the first prerequisite.

Variables from environment

From the manual: “Every environment variable that make sees when it starts up is transformed into a make variable with the same name and value.”

Environment variables may be overriden by passing an -e option through command-line arguments.

More Resources

  • GNU Make Homepage
  • GNU Make Manual
  • GNU Make binaries for Windows
  • manpages for make
  • PRO Courses Guides New Tech Help Pro Expert Videos About wikiHow Pro Upgrade Sign In
  • EDIT Edit this Article
  • EXPLORE Tech Help Pro About Us Random Article Quizzes Request a New Article Community Dashboard This Or That Game Popular Categories Arts and Entertainment Artwork Books Movies Computers and Electronics Computers Phone Skills Technology Hacks Health Men's Health Mental Health Women's Health Relationships Dating Love Relationship Issues Hobbies and Crafts Crafts Drawing Games Education & Communication Communication Skills Personal Development Studying Personal Care and Style Fashion Hair Care Personal Hygiene Youth Personal Care School Stuff Dating All Categories Arts and Entertainment Finance and Business Home and Garden Relationship Quizzes Cars & Other Vehicles Food and Entertaining Personal Care and Style Sports and Fitness Computers and Electronics Health Pets and Animals Travel Education & Communication Hobbies and Crafts Philosophy and Religion Work World Family Life Holidays and Traditions Relationships Youth
  • Browse Articles
  • Learn Something New
  • Quizzes Hot
  • This Or That Game New
  • Train Your Brain
  • Explore More
  • Support wikiHow
  • About wikiHow
  • Log in / Sign up
  • Computers and Electronics
  • Operating Systems
  • Windows Files

How to Make a New File in Windows

Last Updated: December 14, 2022 Tested

This article was co-authored by wikiHow staff writer, Travis Boylls . Travis Boylls is a Technology Writer and Editor for wikiHow. Travis has experience writing technology-related articles, providing software customer service, and in graphic design. He specializes in Windows, macOS, Android, iOS, and Linux platforms. He studied graphic design at Pikes Peak Community College. The wikiHow Tech Team also followed the article's instructions and verified that they work. This article has been viewed 306,796 times. Learn more...

There are many ways to create a file on your Windows PC. Depending on the file you want to create, you'll usually just open an app from the Start menu and use its tools to create the desired type of file. You can also create a blank file from within the File Explorer. This wikiHow teaches you how to create a file on Windows.

Things You Should Know

  • Use File Explorer to make a new file by right-clicking and selecting "New > Text Document" when prompted.
  • Many applications and programs on your Windows 10 computer will allow you to create a new file.

Using File Explorer

Step 1 Open File Explorer icon.

  • You can also open File Explorer by pressing the ⊞ Win + E on the keyboard or by right-clicking the Start menu and selecting File Explorer .

Step 2 Navigate to a folder or your desktop.

  • For example, if you want to create a text file, click Text Document .
  • Notepad can be used to create lots of text-based file type. You can even use it to write programming code , HTML, and more.

Step 7 Type a name for the newly created file.

  • For example, an image editor will have tools to draw, colorize, and select parts of an image.
  • A video editor will have tools that allow you to import video and audio clips, cut, and sequence the video and audio clips.

Step 10 Click the File menu.

  • For example, MS Paint allows you to save an image file as a JPEG, PNG, BMP, or GIF.
  • To edit the file type in Notepad, select All files as the file type and replace the .txt extension with the desired one.
  • For example, to save your file as HTML, replace .txt with .html .

Step 13 Other file types include, .bat for a batch file, .css for a CSS file, .py for a Python file, and .cpp for a C++ file.

Using an Application from the Start Menu

Step 1 Click the Start icon button.

  • If you don't see the application you want to open in the Start menu, type its name into the search bar at the bottom-left corner of the screen to search.
  • You can download and install many free alternatives to paid programs. For example, Libre Office is a free alternative to Microsoft Office, and GIMP is a free alternative to Photoshop. There are also many free video editing programs, such as Shotcut and Openshot .

Step 3 Create and edit your file.

Community Q&A

Community Answer

You Might Also Like

Find Hidden Files and Folders in Windows

About This Article

Travis Boylls

  • Send fan mail to authors

Is this article up to date?

Am I a Narcissist or an Empath Quiz

Featured Articles

What Does a Forehead Kiss Mean? 10+ Reasons Behind This Personal Peck

Trending Articles

8 Reasons Why Life Sucks & 15 Ways to Deal With It

Watch Articles

Fold Boxer Briefs

  • Terms of Use
  • Privacy Policy
  • Do Not Sell or Share My Info
  • Not Selling Info

Keep up with the latest tech with wikiHow's free Tech Help Newsletter

Regex Trap for ITS Disclaimer

CSCI 103 - Spring 2024 Introduction to Programming

Makefile cheat sheet.

By Leif Wesche

Makefiles are tools that help us compile and maintain code locally. Make is a program that comes with the GNU compiler. Makefiles will save you lots of time typing and clicking. You are required to write them for your homework.

How does it work?

  • When you type make or make [target] , the Make will look through your current directory for a Makefile. This file must be called makefile or Makefile .
  • Make will then look for the corresponding target in the makefile. If you don’t provide a target, Make will just run the first target it finds.
  • If the target is found, the target’s dependencies will be run as needed, then the target commands will be run.
  • Oftentimes these commands start with g++ , but they can be anything! You can run any command this way.

The target dependency format looks like this. Note the tab indent before the commands; these are required!

Targets in a Makefile can be named anything (though as you’ll see, certain names can incur certain behavior). Dependencies can either be other targets or file names; if a target depends on another target, it guarantees that target will be run prior, and if a target depends on a file, it will check to see if that file has changed to avoid executing redundantly. Finally, commands can be anything you could run on your command line.

Simple Example

This simple Makefile compiles a hello.cpp program. It also includes a clean target that removes our executable in case we want to clean up the directory.

If we’re in the same directory as our Makefile, we can run the following to compile hello.cpp :

And we can run the following to delete the file we just generated during compilation:

Multi-file Example

It’s important to note a target can be named after after a file . This is most commonly used to:

  • Indicate that our target requires a file that must be compiled by another target.
  • Only run our target when that dependency has changed to avoid doing extra work.

Most of your homeworks will require you to compile multiple files, then link them all at once. To do this, we’ll use the -c compiler flag, which compiles without linking. Note that all the files we compile with -c have target names that correspond to the object files we’re expecting out.

First, take a look at the imaginary file tree we’re basing this Makefile off of:

And now, the Makefile:

There are a couple things to note here:

  • We added a dependency on file1.h to the file1.o target. This makes sure that if file1.h changes, file1.o will be recompiled.
  • Our clean target deletes *.o . This is simply shorthand for deleting all files that end with .o , and is a more convenient way to clean up the objects we created while compiling program .
  • The first target is all . This is simply what the central or default task of a Makefile is customarily called; there’s no rule that requires you to do this. However, having a separate task in charge of orchestrating the overall compilation process can keep your Makefiles tidy.

Using Variables

When you start to write more complicated Makefiles, you’ll find yourself frequently repeating commands and arguments. In order to alleviate this, Makefile offers variables. Here’s an example Makefile where we’ve abstracted most of the g++ calls into variables.

Build Folder

Another way to keep your build process organized is to use a subdirectory for build artifacts. This allows you to keep all of the compiled objects out of the way of the files you’re trying to edit. It also improves the ergonomics of clean ; all you have to do is delete the directory you have all your objects in.

Note that because we still want Make to check file creation and edit times correctly, we also have to change target names. Using a build directory might make your Makefile look something like this:

Special Symbols

There are a bunch of fancy things you can do with Make using wildcard and expanded symbols. Given the following snippet, here are a couple that might come in handy.

  • $@ expands to the target name, i.e. target1
  • $< expands to the first dependency, i.e. dependency1
  • $^ expands to the complete list of dependencies, i.e. dependency1 dependency2

You can use the wildcard operator, % , to apply a rule to multiple files. For example, the following rule compiles all .cpp files in the directory to correspondingly named .o files:

Cheat Sheet

The following is a Makefile template that uses all of the strategies we’ve discussed above. Feel free to use it for your projects, just make sure to modify it to fit our assignment specifications.

make file wiki

Next: Writing Rules , Previous: An Introduction to Makefiles , Up: GNU make   [ Contents ][ Index ]

3 Writing Makefiles

The information that tells make how to recompile a system comes from reading a data base called the makefile .

  • What Makefiles Contain
  • What Name to Give Your Makefile
  • Including Other Makefiles
  • The Variable MAKEFILES
  • How Makefiles Are Remade
  • Overriding Part of Another Makefile
  • How make Reads a Makefile
  • How Makefiles Are Parsed
  • Secondary Expansion

IMAGES

  1. How To Create A Wikipedia Page: A Step-By-Step Guide

    make file wiki

  2. How to Create a New Wikipedia Page

    make file wiki

  3. How to Create a Wikipedia Page (Step by Step)

    make file wiki

  4. How to Create a Wikipedia Page for Your Business

    make file wiki

  5. How To Create A Wikipedia Page: A Step-By-Step Guide

    make file wiki

  6. How to Create a Page in Wikipedia

    make file wiki

VIDEO

  1. How to make windows 11 open file explorer to This PC instead of of Home #windows #howto #tech

  2. How to make file DIY (Natural vegetation and wildlife) (•.•) ♡

  3. Make file more powerful and easy

  4. How to make file

  5. Make file front page (cover page)

  6. how to make file DXF before file.NC in coreldraw

COMMENTS

  1. Make (software)

    In software development, Make is a build automation tool that builds executable programs and libraries from source code by reading files called makefiles which specify how to derive the target program. Though integrated development environments and language-specific compiler features can also be used to manage a build process, Make remains widely used, especially in Unix and Unix-like ...

  2. Make

    GNU Make is a tool which controls the generation of executables and other non-source files of a program from the program's source files. Make gets its knowledge of how to build your program from a file called the makefile, which lists each of the non-source files and how to compute it from other files. When you write a program, you should write ...

  3. GNU make

    suffices to perform all necessary recompilations. The make program uses the makefile data base and the last-modification times of the files to decide which of the files need to be updated. For each of those files, it issues the recipes recorded in the data base. You can provide command line arguments to make to control which files should be recompiled, or how.

  4. GNU Make Manual

    GNU Make Manual Free Software Foundation last updated February 26, 2023. This manual (make) is available in the following formats: HTML (1040K bytes) - entirely on one web page. HTML - with one web page per node.; HTML compressed (212K gzipped characters) - entirely on one web page. HTML compressed (260K gzipped tar file) - with one web page per node.

  5. GNU Make

    We split each long line into two lines using backslash-newline; this is like using one long line, but is easier to read. To use this makefile to create the executable file called `edit' , type: make. To use this makefile to delete the executable file and all the object files from the directory, type: make clean.

  6. michaelfromyeg/makefiles: ⚙️ A guide to Makefiles!

    executable file, a file that when run causes a computer to perform a set of instructions (e.g., the main in gcc main.c -o main) link, meaning to transform many object files (i.e., the things made in compilation) into a single executable file. machine code, a (super) low-level programming language that controls a CPU.

  7. Makefile Tutorial By Example

    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: echo "Hello, World". Note: Makefiles must be indented using TABs and not spaces or make will fail. Here is the output of running the above example: $ make.

  8. make

    A simple compilation process would be by typing the following code by hand: g++ -o file file.cpp. For beginners, this might take a while to get used to. As an alternative, using make the command would be: make file. Both commands will do the same thing - take the file.cpp source file, compile it and then link it into an executable.

  9. What is a Makefile and how does it work?

    Image by: Opensource.com. If you want to run or update a task when certain files are updated, the make utility can come in handy. The make utility requires a file, Makefile (or makefile ), which defines set of tasks to be executed. You may have used make to compile a program from source code.

  10. Introduction (GNU make)

    The makefile can also tell make how to run miscellaneous commands when explicitly asked (for example, to remove certain files as a clean-up operation). To see a more complex example of a makefile, see Complex Makefile Example. When make recompiles the editor, each changed C source file must be recompiled. If a header file has changed, each C ...

  11. Makefile

    A Makefile is a file which controls the 'make' command. Make is available on virtually every platform, and is used to control the build process of a project. Once a Makefile has been written for a project, make can easily and efficiently build your project and create the required output file (s). Make reads dependency information from your ...

  12. Makefile Cheat Sheet

    Targets in a Makefile can be named anything (though as you'll see, certain names can incur certain behavior).Dependencies can either be other targets or file names; if a target depends on another target, it guarantees that target will be run prior, and if a target depends on a file, it will check to see if that file has changed to avoid executing redundantly.

  13. What is a makefile exactly and how we can create one?

    3. A Makefile is used as a "map" for C programs compilation. They work with the make utility, an describe how a program has to be compiled/linked in order to work correctly once turned into a executable file. For global UNIX/shell tasks, you're looking for shell scripts, not makefiles :)

  14. Make (software)

    In software development, Make is a build automation tool that builds executable programs and libraries from source code by reading files called makefiles which specify how to derive the target program. Though integrated development environments and language-specific compiler features can also be used to manage a build process, Make remains widely used, especially in Unix and Unix-like ...

  15. The Basics of GNU Make

    The Basics of GNU Make. A quick guide on getting started with the GNU Make tool and using Makefiles to specify build targets and build dependencies. The make command is commonly used in Linux/Unix environments for building programs from source, but can also be applied for building derivate documents. GNU Make is a tool intended for building ...

  16. GNU Make

    Once a suitable makefile exists, each time you change some source files, this simple shell command: make suffices to perform all necessary recompilations. The make program uses the makefile data base and the last-modification times of the files to decide which of the files need to be updated. For each of those files, it issues the commands ...

  17. Top (GNU make)

    GNU make. This file documents the GNU make utility, which determines automatically which pieces of a large program need to be recompiled, and issues the commands to recompile them. This is Edition 0.77, last updated 26 February 2023, of The GNU Make Manual, for GNU make version 4.4.1.

  18. How to Make a New File in Windows (with Pictures)

    Create and edit your file. Depending on the file type you are creating, you may have to click the File menu and select New to create a new blank file. Once your file is ready, use the tools provided in the application to create and edit your file. 4. Click the File menu.

  19. 'makefile' tag wiki

    A makefile is an input file for the build control language/tool make. It specifies targets and dependencies along with associated commands to perform (a.k.a. recipes) to update the targets. A makefile is usually an input file for the build control language/tool make . The make utility and the corresponding makefile format is standardized by POSIX.

  20. PDF GNU Make

    GNU Make A Program for Directing Recompilation GNU make Version 4.4.1 February 2023 Richard M. Stallman, Roland McGrath, Paul D. Smith

  21. CSCI 103

    Targets in a Makefile can be named anything (though as you'll see, certain names can incur certain behavior).Dependencies can either be other targets or file names; if a target depends on another target, it guarantees that target will be run prior, and if a target depends on a file, it will check to see if that file has changed to avoid executing redundantly.

  22. oss-security

    Please check out the Open Source Software Security Wiki, which is counterpart to this mailing list. Confused about mailing lists and their use? Read about mailing lists on Wikipedia and check out these guidelines on proper formatting of your messages .

  23. Makefiles (GNU make)

    3 Writing Makefiles. The information that tells make how to recompile a system comes from reading a data base called the makefile . What Makefiles Contain. What Name to Give Your Makefile. Including Other Makefiles. The Variable MAKEFILES. How Makefiles Are Remade. Overriding Part of Another Makefile.