CMake子目录依赖

Leo*_*rdo 15 dependencies cmake subdirectory

我是CMake的新手.事实上,我正在尝试通过Kdevelop4 widh C++.

我习惯为我创建的每个命名空间创建子目录,即使所有源都必须编译并链接到单个可执行文件中.好吧,当我在kdevelop下创建一个目录时,它使用add_subdirectory命令更新CMakeLists.txt并在其下创建一个新的CMakeLists.txt,但仅此一项不会将其下的源添加到编译列表中.

我有根CMakeLists.txt如下:


project(gear2d)

add_executable(gear2d object.cc main.cc)

add_subdirectory(component)

在组件/我有我想要编译和链接的源以生成gear2d可执行文件.我怎么能做到这一点?

CMake常见问题解答有这个条目,但如果这是答案,我宁愿留在简单的Makefile.

有办法做到这一点吗?

And*_*dré 18

添加一个子目录并不比CMake指定它应该进入目录并在那里寻找另一个CMakeLists.txt.你仍然需要创建与源文件库add_library并将其与链接到你的可执行target_link_libraries.类似于以下内容:

在子目录CMakeLists.txt中

set( component_SOURCES ... ) # Add the source-files for the component here
# Optionally you can use file glob (uncomment the next line)
# file( GLOB component_SOURCES *.cpp )below

add_library( component ${component_SOURCES} )
Run Code Online (Sandbox Code Playgroud)

Top-dir CMakeLists.txt

project( gear2d )
add_subdirectory( component )
add_executable( gear2d object.cc main.cc )
target_link_libraries( gear2d component )
Run Code Online (Sandbox Code Playgroud)

  • 我想添加将示例中的子目录“组件”重命名为“组件目录”的建议。只是为了明确“target_link_libraries”需要来自子目录的 CMakeLists.txt 中的目标名称“组件”。由于这至少是网络中我发现子目录和链接项具有相同名称的示例的第三个地方,所以我有点困惑,不得不自己尝试一下......(如果子目录名称也适用于`target_link_libraries` - 但事实并非如此;顺便说一句,您也不能使用子目录中定义的 ${...} 别名...) (2认同)