Search

Makefiles: Introduction

Makefiles: Introduction Makefiles are the files used by the utility make. make helps in compiling a source code into an executable or automate execution of commands listed in the makefile.

Let us say we have a file "hello.c"

hello.c



The usual compilation of this in linux using gcc is



We can use a makefile to do the same compilation
The syntax of writing a makefile is



A makefile is comprised of

Target : The executable which has to be generated. In the above case the target is the executable hello.

Prerequisite: The source files required to generated the target. In the above example the source is hello.c

Command: If the prerequisite is available which command will convert it into the target ? The command in the above example is "cc -o hello.c -o hello". The command always has to be preceded by a single tab space

Create a file by the name "Makefile" and enter the contents

Makefile



Now open a terminal and cd to the folder where the makefile is stored.
Run the command



We can see that make has run the command and generated the executable just as we did from the command line.
You might get the following error if you have omitted the tab space before the command.



If you name the makefile wrongly You might get the error



The makefile can also be named with any other name we want but in that case we need to use the option "-f" with the command make. If we want to name the above makefile as my_makefile then we need to use the command make as

After the makefile has generated the executable if we run the command make again we will get the message



This is a special property of the make utility. It will generated a new executable of the mentioned target only if the target does not exist or the source file has been modified after the target has been generated. Next : Makefiles: Dependent targets

No comments:

Post a Comment