CMake 使用惯例
- 在项目根目录建一个 build 目录:
mkdir build && cd build
- 在 build 目录下执行
cmake ..
- 同样在 build 目录下,执行
make
注意上面的
cmake
和make
命令都是在 build 目录下执行,以保证生成的相关cmake
文件在 build 目录下。
Hello World 工程
新建一个项目根目录 Hello-World。
1. 新建 Hello.cpp
#include <iostream>
int main(int argc, char const *argv[])
{
std::cout << "hello cmake" << std::endl;
return 0;
}
2. 新建 CMakeLists.txt
add_executable(hello hello.cpp)
3. 使用 CMake 惯例
3.1 创建 build 目录
├── CMakeLists.txt
├── Hello.cpp
└── build
3.2 进入 build 执行 cmake ..
查看 build 目录下生成的内容:
-rw-r--r-- 1 djimacos staff 14K 11 24 20:13 CMakeCache.txt
drwxr-xr-x 12 djimacos staff 384B 11 24 20:14 CMakeFiles
-rw-r--r-- 1 djimacos staff 5.4K 11 24 20:13 Makefile
-rw-r--r-- 1 djimacos staff 1.6K 11 24 20:13 cmake_install.cmake
3.3 执行 make
再次查看 build 目录下内容,可以看到多了生成的 hello
:
-rw-r--r-- 1 djimacos staff 14K 11 24 20:13 CMakeCache.txt
drwxr-xr-x 12 djimacos staff 384B 11 24 20:14 CMakeFiles
-rw-r--r-- 1 djimacos staff 5.4K 11 24 20:13 Makefile
-rw-r--r-- 1 djimacos staff 1.6K 11 24 20:13 cmake_install.cmake
-rwxr-xr-x 1 djimacos staff 22K 11 24 20:14 hello
3.4 运行 ./hello
可以看到程序的输出内容:
hello cmake