CMakeLists.txt文件写法(6):要求CMake根据指定的源文件生成库文件

本文介绍了如何使用 CMake 的 ADD_LIBRARY 命令来添加一个库目标到项目中,并指定了源文件。可以根据需要设置库类型为 SHARED、STATIC 或 MODULE,默认情况下为 BUILD_SHARED_LIBS 的当前值,若未设置则默认为 STATIC。此外,还可以通过 EXCLUDE_FROM_ALL 选项控制该目标是否默认被构建。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

ADD_LIBRARY: Add a library to the project using the specified source files.

  •   ADD_LIBRARY(libname [SHARED | STATIC | MODULE] [EXCLUDE_FROM_ALL]
    source1 source2 ... sourceN)

    Adds a library target. SHARED, STATIC or MODULE keywords are used to set the library type. If the keyword MODULE appears, the library type is set to MH_BUNDLE on systems which use dyld. On systems without dyld, MODULE is treated like SHARED. If no keywords appear as the second argument, the type defaults to the current value of BUILD_SHARED_LIBS. If this variable is not set, the type defaults to STATIC.

    If EXCLUDE_FROM_ALL is given the target will not be built by default. It will be built only if the user explicitly builds the target or another target that requires the target depends on it.

     

### 回答1: CMake是一个跨平台的构建工具,用于帮助开发者生成各种不同编译工具的构建脚本。在编写CMakeLists.txt文件时,可以使用多个源文件进行编译。 首先,在CMakeLists.txt文件中使用`add_executable`或`add_library`命令来指定生成的可执行文件库文件的名称,并将其与源文件关联起来。 例如,如果我们有两个源文件main.cpp和helper.cpp,我们可以这样写: ```cmake cmake_minimum_required(VERSION 3.12) project(MyProject) add_executable(MyExecutable main.cpp helper.cpp) ``` 这个例子中,我们使用`add_executable`命令来生成一个名为MyExecutable的可执行文件,并将main.cpp和helper.cpp这两个源文件与之关联。 如果我们的项目中有更多的源文件,我们可以继续在`add_executable`或`add_library`命令后面继续添加源文件的名称。 ```cmake add_executable(MyExecutable main.cpp helper.cpp file1.cpp file2.cpp) ``` 当我们构建项目时,CMake会自动将这些源文件编译成目标文件,并链接到生成的可执行文件库文件中。 此外,如果项目中有多个文件夹,并且每个文件夹中都有一些源文件,可以使用`add_subdirectory`命令将这些文件夹添加到构建过程中。 ```cmake add_subdirectory(folder1) add_subdirectory(folder2) ``` 这样可以让CMake在构建过程中进入这些文件夹并执行相应的CMakeLists.txt文件。 总结起来,CMakeLists.txt文件中的多文件编译可以通过`add_executable`或`add_library`命令与源文件进行关联,以及使用`add_subdirectory`命令将多个文件夹添加到构建过程中。 ### 回答2: cmakelists.txt是用于配置CMake编译和构建项目的脚本文件,它使用简单的语法来描述项目的文件结构和依赖关系。如果需要编译多个源文件,可以按照以下步骤编写CMakeLists.txt: 1. 设置项目名称和最低CMake版本: ```cmake cmake_minimum_required(VERSION 3.10) project(MyProject) ``` 2. 添加源文件到项目中,可以使用SET命令将需要编译的源文件路径存储在变量中: ```cmake set(SOURCES src/main.cpp src/other.cpp) ``` 3. 添加可执行文件目标,并将源文件与目标进行关联: ```cmake add_executable(MyExecutable ${SOURCES}) ``` 4. 如果需要链接外部库,可以使用target_link_libraries命令来指定链接的库: ```cmake target_link_libraries(MyExecutable MyLibrary) ``` 完整示例CMakeLists.txt文件: ```cmake cmake_minimum_required(VERSION 3.10) project(MyProject) set(SOURCES src/main.cpp src/other.cpp) add_executable(MyExecutable ${SOURCES}) target_link_libraries(MyExecutable MyLibrary) ``` 以上是最基本的多文件编译的CMakeLists.txt的编写方式,根据实际项目需求,还可以添加更多的配置选项和设置,例如编译选项、包含路径、链接库等。具体的写法会因项目而异。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值