Visual Studio CMake 專案中的 Clang/LLVM 支援

Clang 支援可從 Visual Studio 2019 開始提供。

您可以使用 Visual Studio 搭配 Clang 來編輯和偵錯以 Windows 或 Linux 為目標的 C++ CMake 專案。

Windows :從 Visual Studio 2019 16.1 版開始,Visual Studio 支援在以 Windows 為目標的 CMake 專案中使用 Clang/LLVM 進行編輯、建置和偵錯。

Linux :針對 Linux CMake 專案,不需要任何特殊的 Visual Studio 支援。 您可以使用發行版本的套件管理員來安裝 Clang,並在 CMakeLists.txt 檔案中新增適當的命令。

安裝

如需 Visual Studio 中最佳的 IDE 支援,建議您使用適用于 Windows 的最新 Clang 編譯器工具。 如果您還沒有這些元件,您可以開啟 Visual Studio 安裝程式 並選擇適用于 Windows 的 C++ Clang 編譯器,以使用 C++ 選用元件進行桌面開發。 您可能偏好在電腦上使用現有的 Clang 安裝;如果是,請選擇適用于 v142 建置工具 C++ Clang-cl,或 針對 v143 建置工具 元件選擇 C++ Clang-cl。

Screenshot of the Visual Studio Installer Individual Components page that shows Clang components available for installation.

如需 Visual Studio 中最佳的 IDE 支援,建議您使用適用于 Windows 的最新 Clang 編譯器工具。 如果您還沒有這些元件,您可以開啟 Visual Studio 安裝程式 並選擇適用于 Windows 的 C++ Clang 編譯器,以使用 C++ 選用元件進行桌面開發。 您可能偏好在電腦上使用現有的 Clang 安裝;如果是,請選擇 LLVM 的 MSBuild 支援 (clang-cl) 工具組 元件。

Screenshot of the Visual Studio Installer Individual Components page that shows Clang components available for installation.

建立新的組態

若要將新的 Clang 組態新增至 CMake 專案:

  1. 以滑鼠右鍵按一下 方案總管 中的 CMakeLists.txt,然後選擇 專案的 CMake 設定。

  2. 在 [組態] 下 ,按 [ 新增組態 ] 按鈕:

    Screenshot of the controls at the top of the C Make Settings dialog, with the Add Configuration control highlighted.

  3. 選擇所需的 Clang 組態(請注意,Windows 和 Linux 會提供個別的 Clang 組態),然後按 [選取 ]:

    Screenshot of the Add Configuration to C Make Settings dialog for Clang configuration.

  4. 若要修改此設定,請使用 CMake 設定 編輯器 。 如需詳細資訊,請參閱 在 Visual Studio 中自訂 CMake 組建設定。

修改現有的組態以使用 Clang

若要修改現有的組態以使用 Clang,請遵循下列步驟:

  1. 以滑鼠右鍵按一下 方案總管 中的 CMakeLists.txt,然後選擇 專案的 CMake 設定。

  2. 在 [一般 ] 下 選取 [工具組 ] 下拉式清單,然後選擇所需的 Clang 工具組:

    Screenshot of the General dialog box showing that the Toolset is selected and clang cl x 86 is highlighted.

自訂 Clang 位置

根據預設,Visual Studio 會在兩個地方尋找 Clang:

  • (Windows)Visual Studio 安裝程式隨附之 Clang/LLVM 的內部安裝複本。
  • (Windows 和 Linux)PATH 環境變數。

您可以在 CMake 設定中 設定 CMAKE_C_COMPILER CMAKE_CXX_COMPILER CMake 變數,以指定另一個位置:

Screenshot of the C Make Settings dialog box with the C Make C X X Compiler highlighted.

Clang 相容性模式

針對 Windows 組態,CMake 預設會以 clang-cl 模式叫用 Clang,並使用 Microsoft 實作標準程式庫的連結。 根據預設, clang-cl.exe 位於 C:\Program Files (x86)\Microsoft Visual Studio\2019\Common7\IDE\CommonExtensions\Microsoft\Llvm\bin

您可以在 CMake 變數和快 取下 ,在 CMake 設定 修改這些值。 按一下 [ 顯示進階變數 ]。 向下捲動以尋找 CMAKE_CXX_COMPILER ,然後按一下 [流覽 ] 按鈕以指定不同的編譯器路徑。

編輯、建置和偵錯

設定 Clang 組態之後,您可以建置和偵錯專案。 Visual Studio 會偵測您使用 Clang 編譯器,並提供 IntelliSense、醒目提示、流覽和其他編輯功能。 錯誤和警告會顯示在 [輸出] 視窗中

偵錯時,您可以使用中斷點、記憶體和資料視覺效果,以及其他大部分的偵錯功能。 Clang 組態無法使用某些編譯器相依功能,例如編輯後繼續。

Screenshot of the Visual Studio debugger debugging a CMake Clang project.