Cmake和一个包含源代码的文件夹

cmake and a folder with the source

本文关键字:包含 源代码 文件夹 一个 Cmake      更新时间:2023-10-16
-project
--sourсes
--CmakeList.txt

CmakeList.txt有一个重复:

add_executable(Project1 ${SOURCE_FILES}
    sourсes/File1.cpp sourсes/File1.h
    sourсes/File2.cpp sourсes/File2.h
    ...
)

所有的源代码都在" soursces "文件夹中,这个文件夹不是子项目、模块等。

如何避免重复的"源"在"add_executable"?

我希望能写:

add_executable(Project1 ${SOURCE_FILES}
    File1.cpp File1.h
    File2.cpp File2.h
    ...
)

我发现这是一个例子:

add_sources(PREFIX foo
    ROOT_DIR "sources"
        source_one.cpp
        source_two.cpp
    ROOT_DIR "other/sources"
        source_three.cpp
        source_four.cpp
)
add_executable(foo ${foo_SOURCES})

但是"add_sources"是未知的

可以通过自己的cmakelist.txt添加子目录。

-project
--CmakeList.txt
--sourсes
---CmakeList.txt

所以在根目录下cmakelist.txt看起来像。

add_subdirectory(source)

./source/cmakelist.txt文件看起来像

set(source_path     "${CMAKE_CURRENT_SOURCE_DIR}")
set(sources
     ${source_path}/File1.cpp
     ${source_path}/File1.h
     ${source_path}/File2.h
     ${source_path}/File2.h
     ...
)
add_executable(foo ${sources})

通过这种方式,您可以添加任意多的子目录,而不会污染根目录。

你可以这样做:

set(SOURCES
    File1.cpp File1.h
    File2.cpp File2.h
    ...
)
set(SOURCES_ABS "")
foreach(file IN LISTS SOURCES)
    list(APPEND SOURCES_ABS sources/${file})
endforeach()
add_executable(Project1 ${SOURCES_ABS})