2.5.2. Example: Building a C program using a Makefile
To build a sample C program by using a Makefile, follow the steps in this example.
Prerequisites
Procedure
Create a directory
hellomake:$ mkdir hellomakeChange to the created directory:
$ cd hellomakeCreate a file
hello.cwith the following contents:#include <stdio.h> int main(int argc, char *argv[]) { printf("Hello, World!\n"); return 0; }Create a file
Makefilewith the following contents:CC=gcc CFLAGS=-c -Wall SOURCE=hello.c OBJ=$(SOURCE:.c=.o) EXE=hello all: $(SOURCE) $(EXE) $(EXE): $(OBJ) $(CC) $(OBJ) -o $@ %.o: %.c $(CC) $(CFLAGS) $< -o $@ clean: rm -rf $(OBJ) $(EXE)重要The Makefile recipe lines must start with the tab character. When you copy this example from the documentation, the cut-and-paste process might paste spaces instead of tabs. If this happens, correct the issue manually.
Run
make:$ makegcc -c -Wall hello.c -o hello.o gcc hello.o -o helloThis creates an executable file
hello.Run the executable file
hello:$ ./helloHello, World!Run the Makefile target
cleanto remove the created files:$ make cleanrm -rf hello.o hello
Additional resources