我正在尝试学习cmake
并开始将旧的make
项目转换为cmake
。这是我现在拥有的目录结构的简化版本:
CMakeLists.txt
src/
CMakeLists.txt
main.cpp
core/
CMakeLists.txt
/sourcecode, other cmakes, etc.
test/
CMakeLists.txt
someTest.cpp
目前,在我的根CMakeLists.txt
文件中,我只是这样:
cmake_minimum_required(VERSION 2.8)
project(all)
add_subdirectory(src)
add_subdirectory(test)
我想要做的是,有一个由core/CMakeLists.txt
创建的库,src/CMakeLists.txt
可以使用它来构建主可执行文件,但也可以由test/CMakeLists
加载来构建单元测试
所以我的src/core/CMakeLists.txt
文件目前看起来像这样:
cmake_minimum_required(VERSION 2.8)
project(core)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11 -Wpedantic -Wreorder -DBOOST_TEST_DYN_LINK -DBOOST_LOG_DYN_LINK ")
#some other directories in my core code:
add_subdirectory(display)
add_subdirectory(training)
add_subdirectory(utility)
#some packages I use...
find_package(Boost 1.55.0
COMPONENTS
log
program_options
serialization
thread
system
filesystem
REQUIRED)
find_package(GLUT REQUIRED)
find_package(OpenGL REQUIRED)
find_package(Eigen3 REQUIRED)
include_directories(
${PROJECT_SOURCE_DIR}
${EIGEN3_INCLUDE_DIR})
target_link_libraries(core
display
training
utility
${Boost_LIBRARIES}
${OPENGL_LIBRARIES}
${GLUT_LIBRARY}
${OpenMP_LIBRARIES})
所以我的想法是,我现在有一个core
目标,我可以直接链接来运行我的测试,一切都应该有效。但是,当我尝试构建main
时,我得到:
Cannot specify link libraries for target "core" which is not built by this
project.
我认为这可能是因为core
没有add_library
命令,但如果我添加add_library(core)
,我会收到此错误:
You have called ADD_LIBRARY for library core without any source files. This typically indicates a problem with your CMakeLists.txt file
但我想要添加任何源文件;我只希望此目标链接core
目录中的目标,并生成我可以从test
链接的目标。
显然,我在这里缺少一些核心知识,无论是cmake
还是工具链本身。感谢帮助:)
答案 0 :(得分:2)
如果您只想创建没有源文件的核心目标,则需要将其声明为 INTERFACE 目标。因此,请尝试将以下代码添加到src/core/CMakeLists.txt
:
cmake_minimum_required(VERSION 3.0) # REQUIRED 3.x.x version
project(core)
...
# Here declare your core_interface target
add_library(core_interface INTERFACE)
target_link_libraries(core_interface INTERFACE
display
training
utility
${Boost_LIBRARIES}
${OPENGL_LIBRARIES}
${GLUT_LIBRARY}
${OpenMP_LIBRARIES})
如您所见,如果您这样做,则需要升级CMake安装版本。
然后,您将构建您的测试或任何可执行文件,直接与此接口目标链接:
add_executable(main main.cpp)
target_link_libraries(main core_interface)