我有一个带有一堆子目录的cmake项目,我想要编译的所有子目录都基本相同(子目录本身就是独立的项目,它们只有类似的配置)。 根CMakeLists.txt看起来像:
cmake_minimum_required(VERSION 2.8)
set(CMAKE_TOOLCHAIN_FILE "/path/to/arm-toolchain.cmake")
project(Examples)
set(CMAKE_BUILD_TYPE Debug)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-error")
include_directories("path/to/include")
link_directories("path/to/lib")
add_subdirectory(Foo)
add_subdirectory(Bar)
add_subdirectory(Bob)
add_subdirectory(Encoder)
在每个子目录中,我都有一个类似的CMakeLists.txt:
# Use subdirectory name for executable name.
get_filename_component(OutName ${CMAKE_CURRENT_SOURCE_DIR} NAME)
string(REPLACE " " "_" OutName ${OutName})
file(GLOB Source "src/*.cpp")
add_executable(${OutName} ${Source})
target_link_libraries(${OutName} libtolink)
每个子目录的单个子目录CMakeLists.txt的内容都是相同的。有什么方法可以在cmake中避免为每个子目录复制CMakeLists.txt吗?
答案 0 :(得分:2)
You can declare a function in the parent CMakeLists.txt file:
function(subproject subdir)
# Use subdirectory name for executable name.
get_filename_component(OutName ${subdir} NAME)
string(REPLACE " " "_" OutName ${OutName})
file(GLOB Source "${CMAKE_CURRENT_SOURCE_DIR}/${subdir}/src/*.cpp")
add_executable(${OutName} ${Source})
target_link_libraries(${OutName} libtolink)
set_property(
TARGET ${OutName}
PROPERTY RUNTIME_OUTPUT_DIRECTORY "${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/${subdir}"
) # write the compiled program in the subdirectory
endfunction()
and call it for every subproject, instead of add_subdirectory
:
subproject(Foo)
subproject(Bar)
subproject(Bob)
subproject(Encoder)