To understand this, lets look at a simple "Hello World" program. To begin with, we will use a single source file, "main.c":
Code: Select all
/* File: main.c */
#include <stdio.h>
int main(){
printf("Hello World! \n");
return 0;
}
Code: Select all
/* File: main.c */
#include <stdio.h>
void hello(){
printf("Hello World! \n");
}
int main(){
hello();
return 0;
}
Both of the above files can be compiled by simply issuing: "gcc -c main.c"
What if this program consisted of several very large functions? That is where multiple files come in handy. We could split up the above code across three files, a header and two source code files, like this:
Code: Select all
/* File: hellow.h */
//This is a header file used to declare a function. Any source that
//wants to use the hello() function needs to include this header file.
void hello();
Code: Select all
/* File: hellow.c */
void hello(){
printf("Hello world! \n");
}
Code: Select all
/* File: main.c */
#include <stdio.h>
int main(){
hello();
return 0;
}
To compile this project, we can use: "gcc -o hello hellow.c main.c"
This will create the executable file, hello, from hellow.c and main.c.
To make compiling this project simpler and more flexible, a Makefile could be used. A Makefile is an easy way to organize and compile the source code of a program. The Makefile is used as configuration parameters for the *nix command "make," which tell make how to build your program.
The syntax of a Makefile is:
Code: Select all
target: prerequisites
command
Code: Select all
# File: Makefile
all: hello
hello: hellow.c main.c
gcc -o hello hellow.c main.c
Code: Select all
all: hello
Code: Select all
hello: hellow.c main.c
gcc -o hello hellow.c main.c
Once we have this Makefile in place, we call it like this:
Code: Select all
$ ls
Makefile hellow.c hellow.h main.c
$ make
gcc -o hello hellow.c main.c
$ ls
Makefile hello hellow.c hellow.h main.c
$ ./hello
Hello world!
$
Code: Select all
# File: Makefile
all: hello
hello: hellow.c main.c
gcc -o hello hellow.c main.c
clean:
rm hello
Code: Select all
$ ls
Makefile hellow.c hellow.h main.c
$ make
gcc -o hello hellow.c main.c
$ ls
Makefile hello hellow.c hellow.h main.c
$ ./hello
Hello world!
$ make clean
rm hello
$ ls
Makefile hellow.c hellow.h main.c
$
You could go a step further with this and add an "install" option that copied/moved "hello" to /usr/bin, which would "install" hello by invoking "make install."
This is a very simplistic use of Makefiles. I will probably be making a more complex guide soon, if time permits.