hello-cmake

hello-cmake#

查看 cmake 版本:

!cmake --version
cmake version 4.0.3

CMake suite maintained and supported by Kitware (kitware.com/cmake).

创建缓存目录

temp_dir = ".temp/A-hello-cmake"
!mkdir -p {temp_dir}
%cd {temp_dir}
/media/pc/data/lxw/ai/tao/doc/examples/cmake/01-basic/.temp/A-hello-cmake

编写 C++ 脚本:

%%file main.cpp
#include <iostream>

int main(int argc, char *argv[])
{
   std::cout << "Hello CMake!" << std::endl;
   return 0;
}
Writing main.cpp

编写 CMakeLists.txt

%%file CMakeLists.txt
cmake_minimum_required(VERSION 3.15...4.0) # 设置 CMake 最小版本
project (hello_cmake) # 设置项目名
add_executable(hello_cmake main.cpp) # 添加可执行文件
Writing CMakeLists.txt

使用外部构建,创建可以位于文件系统上任何位置的构建文件夹。所有临时构建和目标文件都位于此目录中,以保持源代码树的整洁。

运行下述代码,新建 build 构建文件夹,并运行 cmake 命令:

!cmake -S. -B build -G Ninja

Hide code cell output

-- The C compiler identification is GNU 15.1.0
-- The CXX compiler identification is GNU 15.1.0
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Check for working C compiler: /media/pc/data/lxw/envs/anaconda3a/envs/xin/bin/cc - skipped
-- Detecting C compile features
-- Detecting C compile features - done
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Check for working CXX compiler: /media/pc/data/lxw/envs/anaconda3a/envs/xin/bin/c++ - skipped
-- Detecting CXX compile features
-- Detecting CXX compile features - done
-- Configuring done (0.9s)
-- Generating done (0.1s)
-- Build files have been written to: /media/pc/data/lxw/ai/tao/doc/examples/cmake/01-basic/.temp/A-hello-cmake/build

然后调用该构建系统来实际编译/链接项目:

!cmake --build build # 等价于 ninja -C build

Hide code cell output

[2/2] Linking CXX executable hello_cmakecmake.dir/main.cpp.o

可以看到,build 文件夹下生成了许多二进制文件:

!ls build/
build.ninja  CMakeCache.txt  CMakeFiles  cmake_install.cmake  hello_cmake

运行可执行文件:

!./build/hello_cmake
Hello CMake!