gpt4 book ai didi

c++ - 如何为具有多个模块(包括单元测试等)的项目设置 cmake

转载 作者:行者123 更新时间:2023-11-28 07:27:32 26 4
gpt4 key购买 nike

好吧,这让我发疯所以我要向你们寻求帮助。我正在尝试建立一个目前非常小的新项目。

为了简单起见,我的项目结构是这样的:
根项目
- module1(仅 header 库)
-- 包括
---模块1
----头文件(包含模板,我想测试一下)
--测试
---testmain.cpp(使用gmock和boost单元测试框架)
-CMakeLists.txt (1)
-module2(另一个库,使用module1)
--与模块1相同的结构
CMakeLists.txt(二)

所以,我有一个根 CMakeLists.txt 和每个模块的几个 CMakeLists.txt。

根 CMakeLists.txt:
`

cmake_minimum_required(VERSION 2.8)
project(root)

# compiler
set(CMAKE_CXX_COMPILER "g++")

# cpp flags
set(CMAKE_CXX_FLAGS "-g -Wall")
add_definitions(-std=gnu++0x)

find_package(Boost COMPONENTS system filesystem unit_test_framework REQUIRED)
set(BOOST_INCLUDES
${Boost_FILESYSTEM_INCLUDE_DIR}
${Boost_SYSTEM_INCLUDE_DIR}
${Boost_UNIT_TEST_FRAMEWORK_INCLUDE_DIR}
)

set(BOOST_LIBRARIES
${Boost_FILESYSTEM_LIBRARY}
${Boost_SYSTEM_LIBRARY}
${Boost_UNIT_TEST_FRAMEWORK_LIBRARY}
)

# Build with system gmock and embedded gtest
set (GMOCK_INCLUDE_DIR "C:/GMock/gmock-1.6.0/include")
set(GMOCK_LIBRARIES gmock gmock_main)

enable_testing()

# Add sub-directories
add_subdirectory (module1)
add_subdirectory (module2)
add_subdirectory (module3)

add_executable(root main.cxx)

但是让 module1 有一个工作的 CMakeLists.txt 让我头疼。哪个是测试仅 header 模块的最简单解决方案?非常感谢您的帮助!

最佳答案

最简单的解决方案是只拉入 module1 的 include 目录,什么都不做。特别是,您不需要为仅 header 模块创建目标:

# Add sub-directories
# add_subdirectory (module1) this we don't need
set(MODULE1_INCLUDE_DIRS "${PROJECT_SOURCE_DIR}/module1/include")
add_subdirectory (module2)
add_subdirectory (module3)

add_executable(root main.cxx)
set_property(TARGET root APPEND PROPERTY INCLUDE_DIRECTORIES ${MODULE1_INCLUDE_DIRS})

另一种方法是为 module1 定义一个方便的目标。不幸的是,自定义目标在过去给我带来了麻烦,所以我现在所做的是在每个仅 header 库中放置一个空的 dummy.cpp 并从中创建一个静态库。这只是为了让 CMake 开心。这允许您执行以下操作:

Module1 CMakeLists

cmake_minimum_required(VERSION 2.8.11)  # 2.8.11 needed for target_include_directories

project("module1")

add_library(module1 STATIC dummy.cpp)
target_include_directories(module1 PUBLIC "${PROJECT_SOURCE_DIR}/include")

主要 CMakeList

[...]

# Add sub-directories
add_subdirectory (module1)
add_subdirectory (module2)
add_subdirectory (module3)

add_executable(root main.cxx)
target_link_libraries(root module1)
# thanks to target_include_directories, this will line
# pull in the correct include paths from module1 for you

这样做的好处是用户根本不必担心任何模块的包含或库是什么。您只需将它们全部传递给 target_link_libraries,它会自动处理所有事情。

关于c++ - 如何为具有多个模块(包括单元测试等)的项目设置 cmake,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18452544/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com