Make/CMake

make和cmake这类工具的用途在于定义各个文件之间的关联

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# VERSION 1
hello: main.cpp printhello.cpp factorial.cpp
g++ -o hello main.cpp printhello.cpp factorial.cpp

# VERSION 2
CXX = g++
TARGET = hello
OBJ = main.o printhello.o factorial.o
$(TARGET):$(OBJ)
$(CXX) -o $(TARGET) $(OBJ)
main.o: main.cpp
$(CXX) -c main.cpp
printhello.o: printhello.cpp
$(CXX) -c printhello.cpp
factorial.o: factorial.cpp
$(CXX) -c factorial.cpp

VERSION 3
CXX = g++
TARGET = hello
OBJ = main.o printhello.o factorial.o

CXXFLAGS = -c -Wall
$(TARGET):$(OBJ)
$(CXX) -o $@ $^

%.o: %.cpp
$(CXX) $(CXXFLAGS) $< -o $@

.PHONY: clean
clean:
del -f *.o $(TARGET)

# VERSION 4
CXX = g++
TARGET = hello
SRC = $(wildcard *.cpp)
OBJ = $(patsubst %.cpp, %.o, $(SRC))

CXXFLAGS = -c -Wall

$(TARGET): $(OBJ)
$(CXX) -o $@ $^

%.o: %.cpp
$(CXX) $(CXXFLAGS) $< -o $@
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
// hello.cpp
#include "functions.h"
#include <iostream>
using namespace std;

int main(){
int i;
printhello();
cout << "This is main:" << endl;
cout << "Factorial of 5: " << factorial(5) << endl;

return 0;
}


//function.h
#ifndef _FUNCTIONS_H_
#define _FUNCTIONS_H_

void printhello();
int factorial(int n);

#endif

// factorial.cpp
# include "functions.h"

int factorial(int n){
if( n == 1){
return 1;
}else{
return n * factorial(n - 1);
}
}
//printhello.cpp
#include <iostream>
#include "functions.h"
using namespace std;

void printhello(){
cout << "Hello, World!" << endl;
}

CMake

可以感受到make不具有很好的跨平台性
CMakeLists.txt:

1
2
3
4
5
6
7
8
9
cmake_minimum_required(VERSION 3.10)

project(HelloWorld)

# set(CMAKE_CXX_STANDARD 11)

file(GLOB SOURCES "*.cpp")

add_executable(hello ${SOURCES})

如果以前安装过ninja,CMake会自动优先使用它,这里指定用Makefile:

1
cmake -G "MinGW Makefiles" .

BestPractice:

1
2
3
4
5
mkdir build
cd build
cmake ..
make
./hello

Make/CMake
https://43.242.201.154/2025/08/18/Make-CMake/
Author
Dong
Posted on
August 18, 2025
Licensed under