共用方式為


C++ 在 Visual Studio 中包含診斷

從 Visual Studio 17.8 開始,Visual Studio 可協助您分析 C++ #include 檔案:

  • 顯示每個頭檔使用的頻率和位置。
  • 顯示每個 #include 檔案的建置時間--這可協助您識別優化建置時間的機會。

啟用 C++ 包含診斷和 CodeLens

C++ Include Diagnostics 功能預設為關閉。 若要開啟它,請在程式碼編輯器中點擊滑鼠右鍵以顯示操作選單,然後選擇 [包含指示詞>開啟 #include 診斷]。

A screenshot of the context menu that appears when you right-click in the code editor area.

操作功能表會顯示反白顯示的 include 指示詞選項,其中顯示兩個選項:Sort # include 指示詞和回合 #包含诊断。

檔案 #include 的相關信息會透過 CodeLens 顯示,預設為關閉。 若要開啟相關的 CodeLens 設定,請流覽至 [工具>選項>] 文字編輯器>[所有語言>CodeLens],並確認 [顯示 C++] #include 參考[顯示 C++ 編譯時間] 都已啟用。

A screenshot of the options window.

選項視窗會設定為 [文本編輯器] > [所有語言] > CodeLens。 顯示 C++ # 包含參考,並醒目提示 [顯示 C++ 編譯時間] 選項。

檢視 #include 參考

若要嘗試包含診斷,請建立新的 C++ 控制台專案。 以下列程式代碼取代主要 .cpp 檔案的內容:

#include <iostream>
#include <vector>

// a function that takes a vector of integers and prints them out
void print(std::vector<int> &vec)
{
    for (int i : vec)
    {
        std::cout << i << std::endl;
    }
    std::cout << std::endl;
}

// a function that takes a vector of integers and adds 10 to each element of the vector and store the result in a new vector
std::vector<int> add10(std::vector<int>& vec)
{
    std::vector<int> newVec;
    for (int i : vec)
    {
        newVec.push_back(i + 10);
    }
    return newVec;
}

int main()
{
    std::vector<int> vec = { 7, 5, 16, 8 };

    print(vec);
    auto newVec = add10(vec);
    print(newVec); 
}

開啟 C++ Include Diagnostics 時,目前程式代碼檔案中會參考頭檔中的程式碼次數會顯示在頭檔上方。 針對先前的程式代碼範例,看起來會像這樣:

6 references
#include <iostream>
5 references
#include <vector>

在程式代碼編輯器中,選取上述 #include <vector> 5 個參考,以及顯示此檔案中使用程式<vector>代碼的位置摘要:

A screenshot of the C++ Include Diagnostics context window showing where code from the vector header file is used.

C++ Include Diagnostics 內容視窗會顯示程式代碼中有五個位置,其中來自向量頭檔的程式代碼用於目前的程式碼檔案。 例如,它會在 add10 函式的定義上使用兩次做為傳回值和參數。 它用於 newVec 宣告的第 17 行,依此方式。

選取專案以移至程序代碼中的位置。

檢視 #include 建置時間

若要查看您 #include每個檔案的建置時間,請先使用 Build Insights 建置。

從主功能表列開啟 [建置深入解析],方法是選取 >[建置] [在方案>組建上執行組建深入解析]。 建置完成之後,會出現一個視窗,列出編譯之各種檔案的建置時間。 返回原始碼視窗,而且每個 #include 檔案的建置時間會顯示在CodeLens中。 看起來會像這樣:

6 references | Build: 0.3560s
#include <iostream>
5 references | Build 0.0360s
#include <vector>

如果您有 #include 不常使用的 指示詞,但會大幅影響您的編譯時間,此工具可協助您識別它。

在本文中,您已瞭解如何開啟 C++ Include Diagnostics 和 CodeLens,以及如何使用 C++ Include Diagnostics 來分析使用 Include 檔案中的項目的頻率,以及影響建置時間的方式 #include

另請參閱

C/C++ 包含清除概觀
包含清除訊息