如何在CMAKE中获取父级项目的名称?

发布于 2025-01-30 18:48:43 字数 963 浏览 2 评论 0原文

请参阅以下最小示例:

├───CMakeLists.txt
├───bar
│   ├───CMakeLists.txt

cmakelists.txt

cmake_minimum_required(VERSION 3.20)
project(foo)
add_subdirectory(bar)

bar/cmakelists.txt

project(bar)
cmake_path(GET CMAKE_CURRENT_LIST_DIR PARENT_PATH BAR_PARENT_DIR)
# how can I get `foo` given ${BAR_PARENT_DIR}?
# or is there a better way to get `foo`?

真正的用例是,最初是foo是通过$ {cmake_project_name}提取的,但是最近有需要使repo subpo兼容。一旦将此存储库用作子模块,$ {cmake_project_name}将不再等于foo。此外,barfoo的子模块,因此我们不允许使用硬代码foo进入bar/cmakelists.txt,因为那会破裂使用bar作为子模块的其他存储库。

有没有办法从父目录中提取cmakelists.txt的项目名称?

编辑:我正在寻找一种解决方案,以使以下方案起作用。含义foo由另一个项目种类。例如

baz
├───CMakeLists.txt
├───foo
│   ├───CMakeLists.txt
│   ├───bar
│        ├───CMakeLists.txt

Please see the below minimal example:

├───CMakeLists.txt
├───bar
│   ├───CMakeLists.txt

CMakeLists.txt

cmake_minimum_required(VERSION 3.20)
project(foo)
add_subdirectory(bar)

bar/CMakeLists.txt

project(bar)
cmake_path(GET CMAKE_CURRENT_LIST_DIR PARENT_PATH BAR_PARENT_DIR)
# how can I get `foo` given ${BAR_PARENT_DIR}?
# or is there a better way to get `foo`?

The real use case is that originally foo was extracted via ${CMAKE_PROJECT_NAME}, but recently there's a need to make the repo submodule compatible. Once this repo is being used as a submodule, ${CMAKE_PROJECT_NAME} won't be equivalent to foo anymore. Additionally, bar is a submodule of foo, so we aren't allowed to hard code foo into bar/CMakeLists.txt because that would break other repos that are using bar as a submodule.

Is there a way to extract the project name of a CMakeLists.txt from a parent directory?

Edit: I am looking for a solution that will make the below scenario work. Meaning foo is submoduled by another project. e.g.

baz
├───CMakeLists.txt
├───foo
│   ├───CMakeLists.txt
│   ├───bar
│        ├───CMakeLists.txt

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

我的鱼塘能养鲲 2025-02-06 18:48:43

是,直接父母的项目名称。

这并不难。 project()命令始终在调用时设置project_name变量。因此,在 you 呼叫project()之前,该变量的值是直接父母的名称。

这没有任何标准,但是实施是微不足道的:

cmake_minimum_required(VERSION 3.23)

set(PARENT_PROJECT_NAME "${PROJECT_NAME}")
project(bar)

if (PARENT_PROJECT_NAME)
  message(STATUS "Found parent: ${PARENT_PROJECT_NAME}")
else ()
  message(STATUS "No parent!")
endif ()

Yes, the project name of the immediate parent.

This is not so hard. The project() command always sets the PROJECT_NAME variable when it is called. So the value of that variable just before you call project() is the name of the immediate parent.

There's nothing standard for this, but it's trivial to implement:

cmake_minimum_required(VERSION 3.23)

set(PARENT_PROJECT_NAME "${PROJECT_NAME}")
project(bar)

if (PARENT_PROJECT_NAME)
  message(STATUS "Found parent: ${PARENT_PROJECT_NAME}")
else ()
  message(STATUS "No parent!")
endif ()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文