在 CMake 中使用 add_subdirectory() 命令来添加和构建子目录(或模块)是一种常见的做法。假设你的项目结构如下:

/MyProject /CMakeLists.txt /Sample-ColorViewer /CMakeLists.txt /src /main.c /other_function.c /include /sample_color_viewer.h

在这个例子中,MyProject 是你的主项目目录,而 Sample-ColorViewer 是一个子模块或子目录,它包含自己的 CMakeLists.txt 文件和一些源代码文件。

主项目 CMakeLists.txt

在主项目的 CMakeLists.txt 文件中,你需要使用 add_subdirectory() 命令来包含并构建 Sample-ColorViewer 子目录。下面是一个示例:

cmake_minimum_required(VERSION 3.10) project(MyProject) # 添加 Sample-ColorViewer 子目录 add_subdirectory(Sample-ColorViewer) # 如果你在主项目中还有其他目标,可以在这里添加 # add_executable(MyExecutable main.c) # target_link_libraries(MyExecutable PRIVATE SampleColorViewer) Sample-ColorViewer 目录的 CMakeLists.txt

在 Sample-ColorViewer 子目录中,你需要一个 CMakeLists.txt 文件来定义如何构建这个模块。以下是一个简单的示例:

cmake_minimum_required(VERSION 3.10) project(SampleColorViewer) # 指定 C 标准(可选) set(CMAKE_C_STANDARD 11) set(CMAKE_C_STANDARD_REQUIRED True) # 包含头文件目录 include_directories(${CMAKE_SOURCE_DIR}/include) # 添加源文件 file(GLOB SOURCES "src/*.c") # 构建库 add_library(SampleColorViewer SHARED ${SOURCES}) # 如果你有其他的依赖项,可以在这里添加 # target_link_libraries(SampleColorViewer PRIVATE SomeOtherLibrary) 编译和链接 生成构建文件:在主项目目录中运行 cmake . 或 cmake -B build(使用单独的构建目录)。 编译项目:运行 cmake --build . 或 cmake --build build(如果你使用了单独的构建目录)。

这样,CMake 会处理 Sample-ColorViewer 子目录,并生成一个共享库(或静态库,如果你将 SHARED 改为 STATIC)。如果你的主项目需要链接这个库,你可以在主项目的 CMakeLists.txt 中添加相应的 target_link_libraries() 命令(如上面的注释所示)。

注意事项 确保 Sample-ColorViewer 目录中的 CMakeLists.txt 文件正确设置了包含目录和源文件。 如果你的库或应用程序需要链接其他外部库,确保在相应的 CMakeLists.txt 文件中添加 find_package() 和 target_link_libraries() 命令。 使用 file(GLOB ...) 来自动包含源文件是一种方便的方法,但它不如显式列出所有源文件那样明确和可靠。在大型项目中,最好显式列出所有源文件。

以上为生成回答,仅供参考~