How to create a MakeFile

Makefile is used compile source codes especially in large projects with many dependencies which will make the compilation difficult. In makefile we will be creating some rules according to which it is executed.Basic Structure of the makefile is

target: dependencies
[tab] system command

So if I want to compile multiple files with dependencies, it would be like

CC = g++
CFLAGS = -g -Wall

default: PersonInfo.o Employee.cpp Employee.h
[tab]$(CC) $(CFLAGS) -c Employee.cpp -o Employee.o

PersonInfo.o: Address.o PersonInfo.cpp PersonInfo.h
[tab]$(CC) $(CFLAGS) -c PersonInfo.cpp -o PersonInfo.o
Address.o: address.cpp address.h
[tab]$(CC) $(CFLAGS) -c address.cpp

The above examples shows the declaration and usage of variables.Here we are using “-c” option with g++, so you will get only the object file and it will not be executable.If you want to generate a executable file,remove “-c” option and execute the command. If you want to link many files to compile a program, you can do that like this.

testCompany: TestCompany address.o PersonInfo.o Employee.o BranchManager.o SalesPerson.o Category.o Customer.o RegCustomer.o Company.o
[tab]$(CC) $(CFLAGS) TestCompany -o testCompany address.o PersonInfo.o Employee.o BranchManager.o SalesPerson.o Category.o Customer.o RegCustomer.o Company.o

Finally you can run the makefile by using the following command.

make

This command will look for “makefile” in the current directory and execute it.Since no options are given along with the make command, first rule will be executed by default. If you have many makefiles in the same directory you can run by using the command,

make -f MyMakefile
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s