Visual Studio 2022 中使用 Clang

May 15, 2022 • 预计阅读时间 2 分钟

本文适用 Visual Studio 2017 以及更高版本

下载 LLVM for Windows

当前最新的 LLVM 版本是 14.0.3,在以下链接可以下载官方编译好的版本:

https://github.com/llvm/llvm-project/releases

  • x86: LLVM-14.0.3-win32.exe
  • x86_64: LLVM-14.0.3-win64.exe
  • arm64: LLVM-14.0.3-woa64.zip

我下载的是 LLVM-14.0.3-win64.exe,安装在目录 C:\Program Files\LLVM-14.0.3

编译 Windows 平台的程序,就需要兼容 MSVC 的扩展和编译选项,所以在 Windows 上使用的前端是 clang-cl.exe

详情参考 LLVM 的文档:MSVC compatibility

在 MSBuild 中使用 Clang

在项目的根目录(就是 .sln 所在目录)下新建一个名称为 Directory.build.props 的项目属性文件:

内容如下,其中安装目录和版本号是必须指定的,否则会出现无法定位 Clang 的错误。

<Project>
  <PropertyGroup>
    <LLVMInstallDir>C:\Program Files\LLVM-14.0.3</LLVMInstallDir>
    <LLVMToolsVersion>14.0.3</LLVMToolsVersion>
  </PropertyGroup>
</Project>

还需要在项目属性中设置平台工具集LLVM (clang-cl)

在 CMake 中使用 Clang

Visual Studio 2017 开始支持打开 CMake 项目。

在 CMake 中使用 Clang 非常简单,只需要设置 CMAKE_CXX_COMPILER 的值为 clang-cl.exe 所在路径就可以了。

根据我自己的安装路径,我设置为 C:/Program Files/LLVM-14.0.3/bin/clang-cl.exe

Clang VS MSVC

虽然在标准实现上 MSVC 全面超越 Clang,但是 Clang 的报错信息友好度是 MSVC 比不了的。

#include <string>
#include <unordered_map>

class Element {
public:
    // 注释掉声明后面的 const 让编译器报错
    std::string name() /* const */ {
        return m_name;
    }

    void insert(const Element& e) {
        // 这里会报错,原因是 name 方法需要是 const 类型
        m_elementMap[e.name()] = e;
    }

private:
    std::string m_name;
    std::unordered_map<std::string, Element> m_elementMap;
};

MSVC 的报错信息:

1>ConsoleApplication1.cpp(62,1): error C2662: “std::string html::Element::name(void)”: 不能将“this”指针从“const html::Element”转换为“html::Element &”
1>ConsoleApplication1.cpp(62,26): message : 转换丢失限定符
1>ConsoleApplication1.cpp(37,21): message : 参见“html::Element::name”的声明

Clang 的报错信息:

1>ConsoleApplication1.cpp(62,26): error : 'this' argument to member function 'name' has type 'const html::Element', but function is not marked const
1>ConsoleApplication1.cpp(37,21): message : 'name' declared here

参考资料

Clang/LLVM support in Visual Studio projects

LLVMClang
版权声明:如果转发请带上本文链接和注明来源。

lvv.me

iOS/macOS Developer

[推荐] 免费的编程字体

Visual Studio 2022 以 UTF-8 编译 CMake 项目