Learn C the Hard Way: Using Makefiles to Build
- Using Make
- What You Should See
- How to Break It
- Extra Credit
We’re going to use a program called make to simplify building your exercise code. The make program has been around for a very long time, and because of this it knows how to build quite a few types of software. In this exercise, I’ll teach you just enough Makefile syntax to continue with the course, and then an exercise later will teach you more complete Makefile usage.
How make works is you declare dependencies, and then describe how to build them or rely on the program’s internal knowledge of how to build most common software. It has decades of knowledge about building a wide variety of files from other files. In the last exercise, you did this already using commands:
$ make ex1 # or this one too $ CFLAGS="-Wall" make ex1
In the first command, you’re telling make, “I want a file named ex1 to be created.” The program then asks and does the following:
- Does the file ex1 exist already?
- No. Okay, is there another file that starts with ex1?
- Yes, it’s called ex1.c. Do I know how to build .c files?
- Yes, I run this command cc ex1.c -o ex1 to build them.
- I shall make you one ex1 by using cc to build it from ex1.c.
The second command in the listing above is a way to pass modifiers to the make command. If you’re not familiar with how the UNIX shell works, you can create these environment variables that will get picked up by programs you run. Sometimes you do this with a command like export CFLAGS="-Wall" depending on the shell you use. You can, however, also just put them before the command you want to run, and that environment variable will be set only while that command runs.
In this example, I did CFLAGS="-Wall" make ex1 so that it would add the command line option -Wall to the cc command that make normally runs. That command line option tells the compiler cc to report all warnings (which, in a sick twist of fate, isn’t actually all the warnings possible).
You can actually get pretty far with just using make in that way, but let’s get into making a Makefile so you can understand make a little better. To start off, create a file with just the following in it.
CFLAGS=-Wall -g clean: rm -f ex1
Save this file as Makefile in your current directory. The program automatically assumes there’s a file called Makefile and will just run it.
This Makefile is showing you some new stuff with make. First, we set CFLAGS in the file so we never have to set it again, as well as adding the -g flag to get debugging. Then, we have a section named clean that tells make how to clean up our little project.
Make sure it’s in the same directory as your ex1.c file, and then run these commands:
$ make clean $ make ex1