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 $
- Phonies: Uses .PHONY for targets that are not files.
.PHONY: clean clean: rm -f $(OBJECTS) $(TARGET)
- Variables: Uses variables to simplify the management of paths and options.
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)Full Example
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 $Good practices
Indent with tabs: Commands in rules must 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 the paths.
Use implicit rules: Take advantage of make's built-in rules to avoid rewriting common rules.
Why use .PHONY?
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 associated commands. .PHONY avoids this.
Performance Improvements: Phony targets are always considered "to do", which may 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.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3