# CMake 错误在 CMakeLists.txt:25 (ament_target_dependencies)：ament_target_dependencies() 调用了未知的目标 'my_library'

- **ID:** `ros2/ros2-ament-cmake-export-dependencies-missing`
- **领域:** ros2
- **类别:** build_error
- **错误码:** `ROS2-4001`
- **验证级别:** ai_generated
- **修复率:** 95%

## 根因

ament_target_dependencies() 引用了一个在调用前未通过 add_library() 或 add_executable() 定义的目标，通常由于缺少或顺序错误的 CMake 命令。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| ros2:humble | active | — | — |
| ros2:iron | active | — | — |
| ament_cmake:1.5.0 | active | — | — |
| cmake:3.22.0 | active | — | — |

## 解决方案

1. ```
   确保在 ament_target_dependencies 之前定义目标。正确顺序示例：
add_library(my_library SHARED src/my_library.cpp)
ament_target_dependencies(my_library rclcpp std_msgs)

如果目标在子目录中，请在引用前使用 add_subdirectory。
   ```
2. ```
   如果目标通过 add_subdirectory 在另一个 CMakeLists.txt 中定义，请确保目标名称完全匹配。验证：
cmake --build . --target my_library  # 检查目标是否存在
   ```

## 无效尝试

- **Adding ament_target_dependencies before add_library in the same CMakeLists.txt** — The target must be defined before dependencies can be added; reordering does not fix the missing target definition. (90% 失败率)
- **Removing all ament_target_dependencies calls and using target_link_libraries directly** — This bypasses ament's dependency handling and may cause missing include paths or compile errors. (60% 失败率)
