# CMake 错误：FetchContent：仓库 https://github.com/user/repo.git 的 git refspec 无效：'refs/heads/mainx' 不是有效引用。

- **ID:** `cmake/fetchcontent-invalid-git-refspec`
- **领域:** cmake
- **类别:** network_error
- **验证级别:** ai_generated
- **修复率:** 92%

## 根因

FetchContent_GitDeclare 或 FetchContent_Populate 指定的 GIT_TAG 指向不存在的分支、标签或提交哈希。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| cmake 3.14 | active | — | — |
| cmake 3.20 | active | — | — |
| cmake 3.27 | active | — | — |

## 解决方案

1. ```
   验证正确的分支/标签名称：运行 'git ls-remote --heads --tags https://github.com/user/repo.git' 列出所有有效引用，然后更新 GIT_TAG，例如 set(FETCHCONTENT_SOURCE_DIR_MYPROJ /local/path) 或更正标签为 'main'。
   ```
2. ```
   如果使用提交哈希，确保它是完整的 SHA（SHA-1 为 40 个字符）并存在于远程：GIT_TAG "abc123def4567890abcdef1234567890abcdef12"。
   ```

## 无效尝试

- **Cleaning the build directory and re-running cmake without changing GIT_TAG** — The refspec is still invalid; cleaning only removes cached content, but the same tag will fail again. (100% 失败率)
- **Setting FETCHCONTENT_UPDATES_DISCONNECTED to ON to skip fetching** — This prevents fetching entirely, so the dependency won't be populated at all, causing a different error. (95% 失败率)
