makefiles, part I

got tired of remembering all compiler and linker switches? I got a good news for you – you can setup everything once and forget about it. One way is to user some studio and create a project, but we are still working from a command prompt. There is command line tool for that – make (or nmake on Windows).

Let’s start with Linux and our hello C example. Using make maybe overkill for one file compilation but it would allow us to see just essential parts of the process. So alongside with hello.c create new file named makefile: vi makefile and type

doit: hello.c
	gcc -g -Wall hello.c -o hello

please note that there should be TAB in front of gcc command, otherwise make would complain.
How to use it? Just type make and by some magic executable file hello should appear.
So how does it work? We created a rule named ‘doit’ (make would execute first rule in your makefile by default) and in this rule we defined that it depends on hello.c, so if hello.c had being changed make should run a command; the command should be on the next line and start with TAB. In our case we call C compiler. Or in general terms:

# comments
target: dependencies

If you want to make sure that what you execute is freshly compiled file you can introduce cleaning rule:

doit: hello.c
	gcc -g -Wall hello.c -o hello

	rm hello

To use if you have to specify it – type: make clean. File hello should disappear.

How about Windows? As a part of compiler command line tools there is make tool as well, it’s called nmake.exe.
And here is how simplest makefile for Windows could look like:

doit: hello.c
	cl.exe hello.c

Create it, same as a makefile and execute nmake.exe (just remember that you have to launch ‘special’ command line prompt otherwise you would get ‘nmake’ is not recognized error)

Leave a Reply