Search

Makefiles: Dependent targets

Prev: Makefiles : Introduction The makefiles can have as many targets as we want, and they could be dependent on another or independent.

Let us say we have the following codes
hello_main.c



print_hello.c



The first program is calling a function declared in the second program. To compile these codes we can run the command



This can be broken down into the following steps
Creating the object code



This will generate the object files "hello_main.o" and "print_hello.o"

Now we can club the object codes into one executable



This will generate the final executable hello.

For creating the executable hello, hello_main.o and print_hello.o are the prerequisites.
Thus the makefile entry for target hello is



For creating the object codes, hello_main.o and print_hello.o are the targets and hello_main.c and print_hello.c are the prerequisites

Thus the make file entries for the two object codes is



Combining the above two we can create the full makefile

makefile:



Note the order in which the entries have been added. The final target is the first entry, the prerequisites for the final target are created by making them as targets in the subsequent entries.

Now run the command make



We can see that make starts compiling from the first independent target hello_main.o then it compiles print_hello.o then it create the final executable using the two object files.

Now open the program print_hello.c and modify the print statement



Save the program and run the command make again.



We can see that make compiled only the modified program and did not compile hello_main.c which was not modified after the executable "hello" was created.

The above split was shown just show the concept of dependent targets. We can compile the same code using the shorter makefile

makefie:



If you misspell any of the prerequisite names then make will throw an error and fail. For eg. if we create the above makefile with the file name hell_print.c



On running make we will get the error



The above error indicates that the problem is with the file name "hell_print.c" as the makefile is unable to find a file with that name. Next: Makefiles :Multiple Independent targets

No comments:

Post a Comment