hello-cmake

hello-cmake#

查看 cmake 版本:

!cmake --version
cmake version 4.1.0

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

创建缓存目录

temp_dir = ".temp/A-hello-cmake"
!mkdir -p {temp_dir}
%cd {temp_dir}
/home/runner/work/tao/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 13.3.0
-- The CXX compiler identification is GNU 13.3.0
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Check for working C compiler: /usr/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: /usr/bin/c++ - skipped
-- Detecting CXX compile features
-- Detecting CXX compile features - done
-- Configuring done (1.5s)
-- Generating done (0.0s)
-- Build files have been written to: /home/runner/work/tao/tao/doc/examples/cmake/01-basic/.temp/A-hello-cmake/build

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

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

Hide code cell output

[0/2] Building CXX object CMakeFiles/hello_cmake.dir/main.cpp.o
[1/2] Building CXX object CMakeFiles/hello_cmake.dir/main.cpp.o
[1/2] Linking CXX executable hello_cmake
[2/2] Linking CXX executable hello_cmake

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

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

运行可执行文件:

!./build/hello_cmake
Hello CMake!