Following on from the previous section, instead of building an executable by hand, you can use a utility called make. make can automate the process of building and linking object files. Furthermore, make will minimize rebuilds - important if some of your source files take a long time to compile. Provided you inform make properly, this utility can also take care of all of you source dependencies for you (e.g. in the last example, hellomake.c depends on hellofunc.c).
To inform make about what to do, you need to create a file called a Makefile.
Putting it into Practice:
|Using the exercise from the previous section, we will instead create a Makefile to make the executable myexecutable. To do this, use emacs to create a file called Makefile, an in this file, type:|
myexecutable: hellomake.o hellofunc.o cc -o myexecutable hellomake.o hellofunc.o hellomake.o: hellomake.c cc -c hellomake.c hellofunc.o: hellofunc.c cc -c hellofunc.c -I.
|WARNING: the 2nd, 4th and 6th lines MUST start with a TAB! This is not just blank space!|
|Now save this file and quit out of emacs. To build your program, at the prompt type:|
|Hit return. This should have built your executable. Try running it by typing at the prompt:|
|Now save this file and quit out of emacs. To run your program, at the prompt type:|
In the above Makefile, there are 3 entries. Each entry comprises a line containing a colon (:) - this is called a dependency line, and one (or more) lines starting with a tab (these are command lines). On the dependency line, the target is to the left of the colon, and to the right of the colon are the target pre-requisites. The command lines instruct how to build the targets out of their pre-requisites.
When make is invoked, the first command line in the file will not be the first that will be executed. First, make will check to see if myexecutable already exists. If it does, make will then check the pre-requesites hellomake.o and hellofunc.o to see if any of these are newer than myexecutable. If your program was built since the latest modifications to hellomake.o and hellofunc.o, make will decide there is no need to rebuild myexecutable, and will just exit without having changed or built anything.
Putting it into Practice:
|You should have all your .o files and the file myexecutable left from the last exercise. Now, see what happens if you try to build your program, by typing (in the usual way..)|
|If everything is up to date, you will get the message to your prompt:|
make: `myexecutable' is up to date.
In general, however, make will also check each of the object (.o) files, to see if the pre-requesites of these objects are up to date. Therefore, if hellofunc.c was last modified after hellofunc.o was built, then make will execute the command to re-compile hellofunc. The same goes for the dependencies of hellomake.o. For example, if hellofunc.c is more recent than hellomake.o, then make will re-build hellofunc.o and