CSC270H1Y- Summer 2001

Using a Makefile with Project 4

For the last project, you are to use a makefile to help you compile your code. A makefile is simply a script that does all the compiling and linking for you. This will make your life a lot easier because you will not have to type all those g++ commands, and it will enable you to change the simulator as much as you wish and the grading scripts will still be able to compile your code.

Makefiles can be a little tricky at first. Because of this, you are going to practice using and modifying an existing makefile rather than trying to write your own.

A complete makefile for the simulator has been provided for you. There are actually two makefiles available, and both can be found on CDF or from links on the web page.
~hsc/classes/270/makefiles/Makefile is the makefile to use if you are using all your own files.
~hsc/classes/270/makefiles/Makefile.libs is the makefile to use if you are using the object files provided for you.
If you want to use some of the provided object files, but not others, you will have to make some very small modifications to the latter makefile.

To use the makefile, copy the desired makefile to your directory. The file will need to be called Makefile or makefile so if you are using the second of the two makefiles above, you will need to rename it. Then copy all the necessary source and include files for the simulator into the same directory as the makefile. You do not need to copy the provided object and header files, just your own code. And then type "make". It is that simple. The routine make will then compile and link your code, and when it finishes, the executable trafficsim will be created and ready to run.

Editing the makefile

If you decide to add or remove files to the simulator, you will need to modify the makefile.

Take a look at the makefile. You will see three types of lines:

If you look at where the main program is compiled, you will see the lines

LD = g++

OBJS = trafficsim.o random_numbers.o network.o cars.o

TARGET = trafficsim

default: $(TARGET)

$(TARGET): $(OBJS)
        $(LD) -o $(TARGET) $(OBJS)

This indicates that the default file to create is trafficsim, trafficsim depends on each of the object files, and to create trafficsim, we have to call the command:

g++ -o trafficsim (all the object files)

If you wish to add a new file to your simulator, you just have to follow the same style. For example, if you want to add the file trafficlights.cpp, use another file, such as cars.cpp as an example. Search the makefile for everywhere that you find the word "cars" and then add in an additional entry for "trafficlights" in the same manner.

Additional Information

If you go to the Links page of the class web page, there is a link to GNUmake which gives a lot more information on makefiles for those who are interested.