包含头文件#

创建缓存目录

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

创建头文件:

%%file include/Hello.h
#ifndef __HELLO_H__
#define __HELLO_H__

class Hello
{
public:
    void print();
};

#endif
Writing include/Hello.h

创建源代码文件:

%%file src/Hello.cpp
#include <iostream>

#include "Hello.h"

void Hello::print()
{
    std::cout << "Hello Headers!" << std::endl;
}
Writing src/Hello.cpp

创建主程序:

%%file src/main.cpp
#include "Hello.h"

int main(int argc, char *argv[])
{
    Hello hi;
    hi.print();
    return 0;
}
Writing src/main.cpp

编写 CMakeLists.txt

cmake_minimum_required(VERSION 3.15...4.0) # 最低CMake版本
project (hello_headers) # 设置项目名
# 创建变量,名字叫 SOURCE。它包含了所有的 cpp 文件链接
set(SOURCES
    src/Hello.cpp
    src/main.cpp
)

# 用所有的源文件生成可执行文件,因为这里定义了 SOURCE 变量,所以就不需要罗列 cpp 文件了
add_executable(hello_headers ${SOURCES})
# 等价于命令:add_executable(hello_headers src/Hello.cpp src/main.cpp)

# 设置在为该目标执行构建命令时应包含的目录
# 运行g++时,这些目录将以 -I/目录/路径/ 的形式被包含进去
target_include_directories(hello_headers
    PRIVATE 
        ${PROJECT_SOURCE_DIR}/include
)
  • PROJECT_SOURCE_DIR 指项目顶层目录

make VERBOSE=1 打印详细信息:

%%bash
cmake -S. -B build -G Ninja
cmake --build build

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.6s)
-- Generating done (0.0s)
-- Build files have been written to: /media/pc/data/lxw/ai/tao/doc/examples/cmake/01-basic/.temp/B-hello-headers/build
[1/3] Building CXX object CMakeFiles/hello_headers.dir/src/main.cpp.o
[2/3] Building CXX object CMakeFiles/hello_headers.dir/src/Hello.cpp.o
[3/3] Linking CXX executable hello_headers

各种可用变量#

Variable

Info

CMAKE_SOURCE_DIR

根源码目录

CMAKE_CURRENT_SOURCE_DIR

当前源码目录(使用子项目/子目录时)

PROJECT_SOURCE_DIR

当前 CMake 项目的源码目录

CMAKE_BINARY_DIR

根构建目录(运行 cmake 命令的目录)

CMAKE_CURRENT_BINARY_DIR

当前所在构建目录

PROJECT_BINARY_DIR

当前项目的构建目录

源文件变量(不建议!)#

创建包含源文件的变量,可以让你更清晰地管理这些文件,并轻松地将它们添加到多个命令中,例如 add_executable()函数。

# Create a sources variable with a link to all cpp files to compile
set(SOURCES
    src/Hello.cpp
    src/main.cpp
)

add_executable(${PROJECT_NAME} ${SOURCES})

在 SOURCES 变量中设置特定文件名的替代方法是使用 GLOB 命令通过通配符模式匹配来查找文件。

file(GLOB SOURCES "src/*.cpp")

对于 modern CMake,不建议对源文件使用变量。不建议使用 glob。

相反,通常直接在 add_xxx 函数中声明源文件。

这对于 glob 命令尤其重要,如果添加新的源文件,这些命令可能不会始终为您显示正确的结果。在 CMake 中指定源文件的最佳方法是明确列出它们。