CMake笔记:Alias Target在哪些地方可以使用

1. 问题描述

以下命令为目标hello增加别名My::Name::Hello

add_executable(hello main.cpp)

add_executable( My::Name::Hello ALIAS hello)

开始在install中使用,

install( My::Name::Hello RUNTIME DESTINATION bin)

出现错误:

CMake Error at src/hello/CMakeLists.txt:8 (install):

install TARGETS given target "My::Name::Hello" which is an alias.

查看cmake文档:

Creates an Alias Target, such that can be used to refer to

in subsequent commands. The does not appear in the

generated buildsystem as a make target.

此句中的generated buildsystem是代码什么,install命令属于generated buildsystem中的吗?

2. generated buildsystem

generated buildsystem 具体指什么

generated buildsystem 指由 构建生成器(如CMake)输出的底层构建系统文件,例如:

  • Makefile(Unix环境)
  • build.ninja (Ninja构建系统)
  • Visual Studio的.vcxproj文件
    这些文件由CMake根据CMakeLists.txt 动态生成,而非用户手动编写。

当定义别名目标(add_executable( ALIAS ))时:

不会出现在生成的Makefile或build.ninja中,它仅是CMake层面的逻辑引用,用于简化脚本编写

3. install 的生成机制

install()命令在CMake配置阶段被解析

其规则会被写入生成的构建系统文件(如Makefile中的install目标)

执行make install时调用的是生成系统中的规则

CMake (元构建系统)

↓ 生成

Makefile/Ninja (具体构建系统)

↓ 执行

编译/安装操作

Alias Target停留在元构建层(CMake作用域)

Install目标下沉到具体构建层(Make/Ninja作用域)

4. 总结

generated buildsystem 指由CMake生成的底层构建文件(如Makefile),Alias Target不会写入此层,仅在CMake抽象层有效。

install命令会显式写入生成的构建系统,通过make install触发,属于构建系统的可执行目标。

两者根本区别在于:

  • Alias Target是配置期的逻辑抽象
  • Install是构建期的物理操作