Friday, June 26, 2009

makefiles

I have been writing makefiles from quite some time now, but for some reason, I could never get them working correctly. ie: If the file is already compiled, a makefile is supposed to do nothing. In case someone else is having the same issues, here goes:

Lets say I want to compile a single cpp file (main.cpp), a header (main.h) and produce an output file (main.o)

this is the simplest makefile:

main.o: main.cpp main.h
    g++ -omain.o main.cpp

The first word "main.o:" refers to the output (compiled) file name. This is called the Target in literature.

The Target must be followed by a colon, and a space separated list of files. This list of files (main.cpp main.h) are called the Dependencies. If you run the makefile, and run it again without making any changes, it wont do any compilation the second time. But if you change any of the Dependencies and then run make again, the files will be recompiled.

Easy enough. Now lets move on to a program with multiple source files. If you have a project with 50 source files, and you change only one file, you dont need to recompile everything again. This is how you do it:

We have 2 source files, and 2 headers: main.cpp, main.h, blah.cpp and blah.h
Let us say we want the output executable name to be final.o
The following is the makefile for such a setup:

final.o: main.o blah.o
    g++ main.o blah.o -ofinal.o

main.o: main.cpp main.h
    g++ -c main.cpp

blah.o: blah.cpp blah.h
    g++ -c blah.cpp


This is what it means: The make file runs the first target. The first target is 'final.o'. final.o is dependent on main.o and blah.o. So, both the Targets 'main.o' and 'blah.o' are called. Note the usage of the compiler flag "-c", which tells g++ not to link the files (since we are compiling them independently). We can link them later, as we shall see.
Now that main.o and blah.o are latest versions, then we can go ahead and link both the object files (yes, if you pass only object files to g++, it links them... much better than using ld).

And there we have it, a makefile!

2 comments:

  1. It is always better to use autotools. No more manual makefile editing.

    btw - ld gives you more options.

    ReplyDelete
  2. So write something about autotools, and we will use it :) Then there are those who advocate cmake, or qmake or whatever...

    hmm, I guess ld does give you more options. but g++ serves my purposes right now...

    ReplyDelete