我有一个使用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吗?
如果我在概念上遗漏了某些东西,或者如果有一个很好的例子我可以用来轻松解决这个问题,那就太好了。
帮助表示感谢,并提前感谢。
答案 0 :(得分:1)
如果您不想使用多个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)
这是an example。