Guides:C/C Crash Course/Makefiles

From CoderGuide

Jump to: navigation, search

Back to TOC


There's another way to compile your programs that will make your life easier, GNU has a handy program called "make" which, based on what's inside of your Makefile, will compile your program for you with one command, make. Also, it will only recompile those parts of your program who's files it depends on have changed since the last time you ran make.

A Makefile (the filename should always be "Makefile" and be in the same directory as your program and code) takes the following form:

# I'm a comment
File-To-Make: File It depends on
        commands needed to make File-To-Make
File-To-Make2: Files It Depends On
        commands needed to make File-To-Make2

The indentation you see there isn't a bunch of spaces, it's actually a single tab. You must always use one or more tabs to offset the commands needed to make your file otherwise GNU make will give you an error like this:

*** missing separator (did you mean TAB instead of 8 spaces?).

Some text editors (not any of the ones I've mentioned) convert tabs to spaces-- You don't want to do this. Borland's Builder editors can strip out tabs and convert them to spaces, so use Notepad, Vim (or any Vi clone, like Elvis), or jEdit instead. Here's a Makefile for the above program (save it as Makefile):

# Makefile for safeio-test
safeio: safeio-test.c safeio.o safeio.h
        gcc safeio-test.c safeio.o -o safeio
safeio.o: safeio.c safeio.h
        gcc -c safeio.c -o safeio.o

What's neat about this is that, if you change safeio.c, then all of the code is recompiled. If you just change safeio-test.c , then only safeio-test.c is recompiled and linked to make the safeio executable. This isn't such a big deal for a small program like this, but, when you have many source files, the this really cuts down on the recompile time of your program if you just make changes to only a few source files. It also dramatically cuts down on the amount of typing you have to do to recompile your program, and reduces the chances you'll make a mistake when doing so.

Now that you have your makefile, and have named it "Makefile", you can compile and run your program with the following commands:


Even though that is a neat little library, we will not use the functions in that library without including them in the source listings below to avoid confusion. Instead, for simplicity, and example purposes only, we'll be using the unsafe gets() function in our programs. This will issue a compiler warning when using the GNU C libraries, but that's okay if we're the only ones using the program and know it's limitations.

Personal tools