A Makefile is a file used by the make tool to automate the compilation of programs. Here are the standard rules and best practices for writing an effective Makefile:
target: prerequisites command
Default rule: The first target in the Makefile is the one that will be built by default.
Compiling source files:
CC = gcc CFLAGS = -Wall -g SOURCES = main.c utils.c OBJECTS = $(SOURCES:.c=.o) TARGET = mon_programme $(TARGET): $(OBJECTS) $(CC) -o $@ $^ %.o: %.c $(CC) $(CFLAGS) -c $< -o $@
.PHONY: clean clean: rm -f $(OBJECTS) $(TARGET)
CC = gcc CFLAGS = -Wall
Dependency management: Uses implicit rules and patterns to reduce repetition.
Automatic dependencies: You can generate dependencies automatically for .o files.
-include $(OBJECTS:.o=.d)
Here is a complete Makefile example:
# Variables CC = gcc CFLAGS = -Wall -g SOURCES = main.c utils.c OBJECTS = $(SOURCES:.c=.o) TARGET = mon_programme # Règle par défaut all: $(TARGET) # Lien de l'exécutable # $@ -> $(TARGET) # $^ -> $(OBJECTS) $(TARGET): $(OBJECTS) $(CC) -o $@ $^ # Compilation des fichiers .c en .o # $< -> Premier element des pr %.o: %.c $(CC) $(CFLAGS) -c $< -o $@ # Déclaration des cibles phony .PHONY: all clean fclean re # Nettoyage des fichiers objets clean: rm -f $(OBJECTS) # Nettoyage complet (fichiers objets et exécutable) fclean: clean rm -f $(TARGET) # Refaire la compilation re: fclean all
Indent with tabs: Commands in rules should be indented with tabs, not spaces.
Comment code: Uses comments to explain sections of the Makefile.
Group files: If your project contains multiple files, organize them into subdirectories and use variables to manage paths.
Use implicit rules: Take advantage of make's built-in rules to avoid rewriting common rules.
Avoid conflicts: If a file with the same name as a target exists, make will think that the target is up to date and will not execute the associated commands. .PHONY avoids this.
Improved performance:Phony targets are always considered "to do", which can improve the speed of execution of associated commands.
Efficiency: Using %.o:%c allows you to benefit from make optimization to only recompile what is necessary.
Practical: For larger projects, %.o:%c is much more suitable.
A well-structured Makefile makes project management easier and avoids compilation errors. By following these rules and best practices, you can create an efficient and maintainable Makefile.
The above is the detailed content of Understanding the Makefile (Example with C language).. For more information, please follow other related articles on the PHP Chinese website!