Mac VSCode Debugger always show error about ';' and ':'

前言

最近想在 Mac M1 設置 Vscode C++ 開發環境,依照 Microsoft 官方 Document 的 Source Code 進行測試,總是會莫名的出現錯誤

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <vector>
#include <string>

using namespace std;

int main()
{
vector<string> msg {"Hello", "C++", "World", "from", "VS Code", "and the C++ extension!"};

for (const string& word : msg)
{
cout << word << " ";
}
cout << endl;
}

仔細研究一下錯誤訊息,嗯…
這個案情並不單純啊!

1
2
3
4
5
6
7
8
test2.cpp:9:23: error: expected ';' at end of declaration
vector<string> msg {"Hello", "C++", "World", "from", "VS Code", "and the C++ extension!"};
^
;
test2.cpp:11:29: warning: range-based for loop is a C++11 extension [-Wc++11-extensions]
for (const string& word : msg)
^
1 warning and 1 error generated.

仔細分析了 tasks.json,發現這個問題主要是因為 problemMatcher 這個參數所引起的,其解決辦法如下

- 問題分析

這個問題主要是因為 problemMatcher 無法用正確的 C++ 版本進行判斷
This error is caused by problemMatcher judgment.

- 解決辦法

  1. 開啟 Vscode 的設定
    Settings will open up.

  2. 尋找 code-runner: Executor Map,並進行編輯 settings.json.
    Find code-runner: Executor Map and click on the edit in settings.json.

  3. 尋找 cpp,並在 cd $dir && g++ 後方添加 -std=c++17,以指定 C++ 版本,如下圖所示
    Find the cpp and add ``-std=c++17aftercd $dir && g++ Like this“cpp”: “cd $dir && g++ -std=c++17 $fileName -o $fileNameWithoutExt && $dir$fileNameWithoutExt”, `

  4. 儲存完後,這個問題應該就可以解決了,可以再試看看!
    Save it, and you are all done! You can try again.