C++ Details about Makefile include generic templates
- 2020-06-12 10:13:17
- OfStack
introduce
Makefile is a script file that specifies how to compile and link programs. When executing make command, it will be executed. IDE in window environment, such as visual studio, has been integrated with this function.
make is a command tool that explains the instructions in Makefile and is integrated with the common IDE. The current centos 7.3 GNU version of make is 3.82
The rules
Target file: Dependent file
[Tab] System Instruction 1 (Note: System instruction must be preceded by tab)
use
3.1 Simple use
main.cpp test.cpp ES40en.es41EN3 files, Makefile incremental compilation (recompiling the file when one of them changes)
helloworld: main.o test.o
g++ main.o test.o -o helloworld
main.o: main.cpp test.h
g++ -c main.cpp -o main.o
test.o: test.cpp test.h
g++ -c test.cpp -o test.o
clean:
rm *.o helloworld
3.2 makefile USES comments, variables and functions
Note:
Precede the line with a "#" such as #g++ main.o test. o-o helloworld indicates that the line is annotated
Variables:
Define a variable with = and assign a value to it. Appends the string with += Get the value of the variable with $(A)Ex. :
A = src
echo $(A)
@echo $(A) ## Only the output echo Does not show the command executed
Special variables:
$@ destination file $^ list of dependencies $ < Dependency list item 1Function:
There are 1 predefined functions in Makefile, in the form of:
$(function name argument list)
Parameter list: Separated by commas
Function names and arguments are separated by Spaces
Get the current directory path
PWD = $(shell pwd)
Get all.cpp files in the current directory
CXX_SOURCES = $(wildcard *.cpp)
# Gets all the.cpp files compiled from the current directory.o
CXX_OBJECTS = $(patsubst *.cpp *.o, $(CXX_SOURCES))
3.3 Optimize Makefile in 3.1
EXE = helloworld
GCC = g++
$(EXE): main.o test.o
$(GCC) $^ -o $(EXE)
main.o: main.cpp test.h
$(GCC) -c $< -o $@
test.o: test.cpp test.h
$(GCC) -c $< -o $@
clean:
rm *.o $(EXE)
3.4 Optimize Makefile in 3.3
Continue to optimize Makefile, add folders, put source code into src and lib folders, keep incremental compilation, that is, Makefile generic template
EXE = helloworld
GCC = g++
SUBDIR = src lib
CPP_SOURCES = $(foreach dir, $(SUBDIR), $(wildcard $(dir)/*.cpp))
CPP_OBJECTS = $(patsubst %.cpp, %.o, $(CPP_SOURCES))
DEP_FILES = $(patsubst %.o, %.d, $(CPP_OBJECTS))
$(EXE): $(CPP_OBJECTS)
$(GCC) $(CPP_OBJECTS) -o $@
%.o: %.cpp
$(GCC) -c -MMD $< -o $@
-include $(DEP_FILES)
clean:
rm $(CPP_OBJECTS) $(EXE)
This Makefile can be used as a general Makefile template to compile C/C++ project
conclusion