Thursday, September 3, 2009

Makefile

Compiling the source code of your program/project on Linux/UNIX system is tedious, specially when program/project has several source files and you have to type command every time you want to compile it.

There is a utility called make to build the applications.   Make looks for a text file in the current directory called "makefile" or "Makefile" to execute.  Makefile is a file that instructs the program make how to compile and link a program. In this post I will explain, how to use GNU make utility with Makefiles. 

How to write comments in the makefile:
The comment in the Makefile is indicated by the comment character “#”. All text from the comment character to the end of the line is ignored.
Example:
# This is the comment in the Makefile
# Comment

How to define Variable in the Makefile:
You can define variable in the makefile.  Variable definition format is as follows:
VARNAME = Value
For example, Lets define a variable and set it to the compiler which I want to use to compile my program code.
CC = g++
CC is the variable name and g++ is the compiler I want to use to compile my program. 
 
How to use the variable:
We have define the variable CC above, now let me explain you, how to use it.
To use the variable syntax is as follows:
$(VARNAME)
In our example, we define CC variable, we can access the variable as follows:
$(CC) 
 
How to compile program using command line:
Suppose my program name is myprog.cpp. To compile it, I have to type following command:
g++ -o myexe myprog.cpp
 
Whereas myexe is an executable file name and myprog.cpp is the source file of my program.
If I want to compile my program multiple times then I have to issue this command multiple times.
Things become more complicated when I need to give some parameter to compile my program such as 
optimization parameters, library paths, etc.
 
Makefile comes for rescue here.  Create a new text file and named it as Makefile. Do not give any extension to it. 
Simply put the command (g++ -o myexe myprog.cpp) in the makefile, save the file, and at command
prompt type make
#Makefile
     g++ -o myexe myprog.cpp

Now suppose we have three source files namely mainprog.cpp, file1.cpp and file2.cpp.

Then you can create a makefile as follows:
g++ -c -o file1.o file1.cpp
g++ -c -o file2.o file2.cpp
g++ -o myexe mainprog.cpp file1.o file2.o
 
You can now make use of variables and can make the Makefile much simpler as shown below:
 
COMPILER=g++
OBJS=mainprog.o file1.o file2.o
default: myapp
myapp: $(OBJS)
 $(COMPILER) -o myexe $(OBJS)
 
You only need to issue only the make command everytime you want to compile you program, that's it.
If the source file in your project increses then you only have to add filename.o to 
OBJS variable list, that's it. Very simple. 

No comments:

Post a Comment