如何在CLion中通过Ninja让CMake自动适配x64架构
解决Ninja+CMakePresets在CLion中默认x86、指定x64报错的问题
问题根源
Ninja生成器依赖环境变量确定编译架构,不支持直接传递platform参数。你之前的CMakePresets.json中设置architecture和toolset的strategy为external,导致CMake尝试将x64平台参数传给Ninja,触发报错。同时CLion默认加载x86环境,需自动调用vcvarsall.bat x64配置x64编译环境。
解决方案
1. 修改CMakePresets.json配置
移除导致报错的architecture和toolset字段,通过command字段自动检测Visual Studio路径并调用vcvarsall.bat x64,确保配置前加载x64环境。修改后的完整配置如下:
{ "version": 3, "configurePresets": [ { "name": "windows-base", "description": "Target Windows with the Visual Studio development environment.", "hidden": true, "generator": "Ninja", "binaryDir": "${sourceDir}/Build/${presetName}", "installDir": "${sourceDir}/Install/${presetName}", "command": [ "cmd.exe", "/C", "for /f \"tokens=*\" %%i in ('\"C:/Program Files (x86)/Microsoft Visual Studio/Installer/vswhere.exe\" -latest -products * -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 -property installationPath') do call \"%%i/VC/Auxiliary/Build/vcvarsall.bat\" x64 && cmake" ], "cacheVariables": { "CMAKE_C_COMPILER": "cl.exe", "CMAKE_CXX_COMPILER": "cl.exe" }, "condition": { "type": "equals", "lhs": "${hostSystemName}", "rhs": "Windows" } }, { "name": "x64-debug", "displayName": "Debug", "description": "Target Windows (64-bit) with the Visual Studio development environment. (Debug)", "inherits": "windows-base", "cacheVariables": { "CMAKE_BUILD_TYPE": "Debug" } }, { "name": "x64-release", "displayName": "Release", "description": "Target Windows (64-bit) with the Visual Studio development environment. (Release)", "inherits": "windows-base", "cacheVariables": { "CMAKE_BUILD_TYPE": "Release" } }, { "name": "x64-release_with_debug_information", "displayName": "Release with Debug Information", "description": "Target Windows (64-bit) with the Visual Studio development environment. (RelWithDebInfo)", "inherits": "windows-base", "cacheVariables": { "CMAKE_BUILD_TYPE": "RelWithDebInfo" } } ], "buildPresets": [ { "name": "Debug Preset", "configurePreset": "x64-debug" }, { "name": "Release Preset", "configurePreset": "x64-release" }, { "name": "Release with Debug Information Preset", "configurePreset": "x64-release_with_debug_information" } ] }
配置细节说明
command字段:通过vswhere.exe自动查找最新Visual Studio安装路径,调用vcvarsall.bat x64配置x64环境后再执行CMake,避免硬编码VS路径,适配不同VS版本。- 移除
architecture/toolset:Ninja无需直接平台参数,依赖环境变量确定架构,解决报错问题。 condition字段:限制该预设仅在Windows系统生效。
2. 在CLion中应用预设
- 打开
File > Settings > Build, Execution, Deployment > CMake。 - 在
Configure preset下拉菜单中选择目标x64预设(如x64-debug),清空CMake options中的无关内容。 - 点击
Apply,重新加载CMake项目。
3. 验证x64环境生效
可通过以下方式验证:
- 查看CMake缓存中的
CMAKE_SIZEOF_VOID_P值,若为8则表示x64环境生效。 - 添加测试代码编译运行:
#include <iostream> int main() { std::cout << "Pointer size: " << sizeof(void*) << " bytes" << std::endl; return 0; }
输出8 bytes即为x64环境配置成功。
内容的提问来源于stack exchange,提问作者Nima Ghorab
相关产品推荐
相关产品推荐

