I want to show you some information and an example of how to write a Makefile, something you may want to do in your project.
There is detailed information about this topic in Appendix2 of Dive into Systems. In this chapter is a link to a generic general purpose Makefile (in section 17.5.10) that you can download and edit for your own use.
Although you can write a Makefile from scratch, often once you write one, or have one example, you can use it as a starting point for writing a new one.
What is make and Makefiles
make
is a command that can be run to execute a set of commands from a
Makefile
. Most commonly, Makefiles are used to build executable files from
source files, header files, and linking in library code. The Makefile
contains all the rules that will be executed when the user runs make
. For programs built from many files, for programs with long compilation command lines, writing and using make files is a much easier way to compile and build programs; just type make
, or make clean
to clean up all compiled files.
Example Makefile
Let’s look at Part2 of Lab2, the multithreaded client and chat server as an example. We are going to look at its Makefile to understand what it is doing. I’ll try to write another one by scratch that also works as we go
This assignment is different from many others in that there are two separate executable files to build: the client and the server. More often a Makefile is used to build a single executable. The examples in Appendix2 of Dive into Systems are these kind.
The Lab 2 Makefile that has the following characteristics:
-
builds two executable files,
cs87_client
, andcs87_server
. -
has multiple
.c
and.h
files from which executables are built. -
we want to explicitly compile .c to .o and then link .o into executables (this is because both the client and the server use cs87talk.c, so we only want to compile it one time).
-
requires explicity linking in library code. One way we know when this is the case is by looking at the man page for a function in the library. For example:
man pthread_create
We are going to look at:
-
defining and using Makefile variables
-
Makefile rules (or target entries, or recipes).
-
dependencies and what gets compiled when a file changes
References
-
Appendix2 of Dive into Systems. At the end of the section on make are several links to other resources.