决定在CMakeLists.txt中写什么-主要是在子文件夹中

Deciding what to write in CMakeLists.txt - mainly in subfolders

本文关键字:文件夹 什么 CMakeLists txt 决定      更新时间:2023-10-16

我有一个使用CMake和gtest的简单项目。我有一个基本的CMakeLists.txt文件工作,但我想更好地了解如何使用多个CMakeLists.txt的并连接它们。到目前为止,该项目的代码如下:

https://github.com/dmonopoly/writeart/tree/10b62048e6eb6a6ddd0658123d85ce4f5f601178

为了更快的参考,我利用的唯一的CMakeLists.txt文件(在项目根目录中)在里面有这个:

cmake_minimum_required(VERSION 2.8)
# Options
option(TEST "Build all tests." OFF) # makes boolean 'TEST' available
# Make PROJECT_SOURCE_DIR, PROJECT_BINARY_DIR, and PROJECT_NAME available
set(PROJECT_NAME MyProject)
project(${PROJECT_NAME})
set(CMAKE_CXX_FLAGS "-g") # -Wall")
#set(COMMON_INCLUDES ${PROJECT_SOURCE_DIR}/include) if you want your own include/ directory
# then you can do include_directories(${COMMON_INCLUDES}) in other cmakelists.txt files
################################
# Normal Libraries & Executables
################################
add_library(standard_lib Standard.cpp Standard.h)
add_library(converter_lib Converter.cpp Converter.h)
add_executable(main Main.cpp)
target_link_libraries(main standard_lib converter_lib)
################################
# Testing
################################
if (TEST)
    # This adds another subdirectory, which has project(gtest)
    add_subdirectory(lib/gtest-1.6.0)
    enable_testing()
    # Include the gtest library
    # gtest_SOURCE_DIR is available due to project(gtest) above
    include_directories(${gtest_SOURCE_DIR}/include ${gtest_SOURCE_DIR})
    ##############
    # Unit Tests
    ##############
    # Naming
    set(UNIT_TESTS runUnitTests)
    add_executable(${UNIT_TESTS} ConverterTest.cpp)
    # standard linking to gtest stuff
    target_link_libraries(${UNIT_TESTS} gtest gtest_main)
    # extra linking for the project
    target_link_libraries(${UNIT_TESTS} standard_lib converter_lib)
    # This is so you can do 'make test' to see all your tests run, instead of manually running the executable runUnitTests to see those specific tests.
    add_test(NAME myUnitTests COMMAND runUnitTests)
endif()

我的目标是移动Standard.cpp和Standard.h到lib/。当我这样做的时候,虽然,我发现我在CMakeLists.txt中所做的排序很复杂。我需要我的gtest设置库,但库必须在lib/CMakeLists.txt中制作,对吧?查找所有库和可执行文件的位置是否会变得非常复杂,因为您必须查看所有CMakeLists.txt文件?

如果我在概念上遗漏了什么,或者如果有一个很好的例子我可以用来轻松地解决这个问题,那将是伟大的。

感谢您的帮助。

如果不想使用多个CMakeLists.txt文件,就不要使用。

################################
# Normal Libraries & Executables
################################
add_library(standard_lib lib/Standard.cpp lib/Standard.h)
add_library(converter_lib lib/Converter.cpp lib/Converter.h)
# Main.cpp needs to know where "Standard.h" is for the #include, 
#   so we tell it to search this directory too. 
include_directories(lib)

如果您想要多个CMakeLists.txt,您可以将其移出:

# Main CMakeLists.txt:
add_subdirectory(lib)
include_directories (${standard_lib_SOURCE_DIR}/standard_lib) 
link_directories (${standard_lib_BINARY_DIR}/standard_lib) 

/lib/CMakeLists.txt中:

add_library (standard_lib Standard.cpp)