Makefiles: Multiple independent targets

Prev: Multiple dependent targets

The make command when executed with out any arguments always tries to create the first target. But in one makefile we can specify as many independent targets as we want and then choose to create the specific targets .

Let us say we have two programs

hello_1.c

#includemain() { printf(“Hello world”); }

hello_2.c

#includemain() { printf(“Hello universe”); }

The above two are independent programs which can be compiled on the command line using

$ cc -o hello_1 hello_1.c $ cc -o hello_2 hello_2.c

The same can be done by creating a makefile with two targets “hello_1” and “hello_2”.

makefile:

hello_1: hello_1.c cc -o hello_1 hello_1.c hello_2: hello_2.c cc -o hello_2 hello_2.c

Now if we run the command make

$ make cc -o hello_1 hello_1.c

We can see that if use the command make with no arguments the first target i.e. hello_1 gets crated. Now if we want to create the second target we will have to pass the second target to the make command as an argument.

$ make hello_2 cc hello_2.c -o hello_2

Thus we can specify any specific target we want to create as the argument to the command make.

If we want to option of creating all the independent targets with out specifying every target separately we add a target to the makefile and mention all the targets as the dependencies.

makefile:

all: hello_1 hello_2 hello_1: hello_1.c cc -o hello_1 hello_1.c hello_2: hello_2.c cc -o hello_2 hello_2.c

Now we can create hello_1 and hello_2 by running make with all as the target.

$ make all cc -o hello_1 hello_1.c cc -o hello_2 hello_2.c

Thus we can use makefile with multiple targets and selectively create the required targets or create all of them together.

Next: Makefiles: make is smart


Tags: ,
Copyright 2017. All rights reserved.

Posted October 16, 2012 by Tux Think in category "Linux