Search This Blog

Friday, January 14, 2011

'make'ing life easy with 'Makefile'

It was a long time since I wished to try my hands on 'make' utility. I had done some basic study about 'make' and 'Makefile's about 3 years back. Now that I got a day off from office for 'Sankranthi' I thought this would be the day I realize my wish. After about 3 hours of experimenting with 'Makefile' I was able to write a simple make file that worked with my setup. I'm setup with MinGW on windows and my 'make' has come from 'msys 1.0'. 

          A basic 'Makefile' statement has 3 parts 'Target", "dependencies" and "build rules" in the following format:
Target: dependencies
 <tab> build rules

Example:
hello:   hello.c
<tab> gcc -o hello hello.c

Note: <tab> is very important at the beginning of any rule. If missed, make will give errors.

If this is simply interpreted as per basic format, hello is the final exe file which is built from hello.c using the command gcc -o hello hello.c.

A simple Makefile that I ended up writing is as follows:


Liking necessary object files to build an executable did not come easily to me. Figuring out the necessary libraries and their paths was one hell of a task. I eventually succeeded in doing it after lot of trial-and-errors.

The "lib_objs =   c:/mingw/lib/crt2.o c:/mingw/lib/gcc/mingw32/3.4.5/crtbegin.o c:/mingw/lib/gcc/mingw32/3.4.5/crtend.o" are the necessary object files from the library required to build an exe. Apart from these object files, we also need libgcc, libmingw32, libmsvcrt and libkernel32 libraries. These dependencies are collected in make file variable "Libs" in the line: "Libs = -lgcc -lmingw32 -lmsvcrt -lkernel32". It is also important that path to these libraries is given to the linker. All these paths are collected in the linker variable "Lib_paths" as in the line" Lib_paths = -Lc:/mingw/lib -Lc:/mingw/lib/gcc/mingw32/3.4.5".


    ld -o MyProg.exe hello.o $(lib_objs) $(Lib_paths) $(Libs)  is the line that links the user object file hello.o with the dependencies from library to build the exe.


hello.o is compiled from hello.c with the line:     gcc -c hello.c

Note: It's good practice to define all necessary variables at the beginning of the file.