天天看點

mac 使用Clang配置VS Code C/C++環境準備

目錄

  • 準備
    • 把VS Code 添加到環境變量中
    • 在檔案夾中打開VS Code
    • 配置編譯路徑
    • 建立build(連結) task
    • 配置調試設定
    • Add a source code file
    • 探索智能提示(IntelliSense)
    • Build the program
    • Start a debugging session
    • Step through the code
    • Set a watch

Clang 是一個C、C++、Objective-C和Objective-C++程式設計語言的編譯器前端。它采用了LLVM作為其後端,而且由LLVM2.6開始,一起釋出新版本。它的目标是提供一個GNU編譯器套裝(GCC)的替代品,支援了GNU編譯器大多數的編譯設定以及非官方語言的擴充。作者是克裡斯·拉特納(Chris Lattner),在蘋果公司的贊助支援下進行開發,而源代碼許可是使用類BSD的伊利諾伊大學厄巴納-香槟分校開源碼許可.

本教程的環境是macOS,是以要在vscode中使用Clang/LLVM來編譯和調試,在配置完vscode後,你會編譯和調試一個簡單的小程式來熟悉vscode.

準備

  1. 下載下傳vscode
  2. 下載下傳C++ extension
    mac 使用Clang配置VS Code C/C++環境準備

把VS Code 添加到環境變量中

為了能從指令行中直接打開VS Code,我們需要把VS Code的路徑添加到環境變量中,這個隻需要在第一次使用時配置一次即可

  1. 打開VS Code.
  2. 按 ⇧⌘P 打開Command Palette.
  3. 輸入“Shell”,然後從清單中選擇 Shell Command: Install ‘code’ command in PATH.
    mac 使用Clang配置VS Code C/C++環境準備
  4. 你會在VS Code的右下角看到一個通知,告訴你VS Code已成功加入到環境變量中.
  5. 關閉VS Code.

在檔案夾中打開VS Code

In the macOS Terminal, create an empty folder called “projects” and then a subfolder called “helloworld”. Navigate into it, and open VS Code (code) in that folder (.) by entering the following commands:

在 mac 的Terminal 中建立一個叫做“projects”的空檔案夾,然後建立一個叫做“helloworld”的子檔案夾,在目前檔案夾中打開vscode.具體指令如下:

mkdir projects
cd projects
mkdir helloworld
cd helloworld
code .
           

**code .**的意思是從目前檔案夾中打開VS Code,同時這個檔案夾會成為你的workspace,為了能夠智能提示、編譯以及調試你的代碼,你還要配置VS Code來使用Clang/LLDB,在完成這些配置後,你會在

.vscode

子檔案夾裡看到三個檔案.

mac 使用Clang配置VS Code C/C++環境準備
  • c_cpp_properties.json

    (編譯路徑和智能提示設定)
  • tasks.json

    (連結指令)
  • launch.json

    (調試設定)

為了重複使用這些配置,你可以把這三個檔案複制到新的workspace中,然後把程式名字和其他的配置改成你需要的設定.

配置編譯路徑

  1. 按⇧⌘P 打開Command Palette,像這樣
    mac 使用Clang配置VS Code C/C++環境準備
  2. 輸入 “C/C++” 然後從清單中選擇 Edit Configurations (UI),這就會打開 C/C++ 的配置頁面,當你在這裡改變設定, VS Code 會将你改變的設定寫入到叫做

    c_cpp_properties.json

    的檔案中,該檔案存在于

    .vscode

    檔案夾.
    mac 使用Clang配置VS Code C/C++環境準備
  3. 找到 Compiler path 設定,VS Code 會試着找到Clang的路徑并填入其中, 這個路徑應該是:

    /usr/bin/clang

    .

    Compiler path 設定在你的配置中是非常重要的一個設定,C++的插件會根據它來找到C++标準庫頭檔案的路徑,當插件知道這些檔案在哪兒時,它可以在你寫代碼時提供大量的有用資訊,這些資訊叫做智能提示,稍後你會看到一些例子.

  4. 設定 IntelliSense mode 為 ${default}, 這個在mac中是clang-x64.
  5. You only need to modify the Include path setting if your program includes header files that are not in your workspace or in the standard library path如果你的程式包含一些沒有在你workspace或者沒在标準庫路徑中的頭檔案時,你需要把它的路徑添加到這兒來,比如我的:
    mac 使用Clang配置VS Code C/C++環境準備
${workspaceFolder}/**
/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include
           
  1. 在mac中, 你必須設定 macFrameworkPath (在Advanced Settings中)來指向系統頭檔案.
    mac 使用Clang配置VS Code C/C++環境準備
/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/System/Library/Frameworks
/System/Library/Frameworks
/Library/Frameworks
           

Visual Studio code 會将這些設定寫入到

.vscode/c_cpp_properties.json

. 如果你直接打開這個檔案 它應該長得像這樣 (這依賴于你自己具體的路徑:

{
    "configurations": [
        {
            "name": "Mac",
            "includePath": [
                "${workspaceFolder}/**",
                "/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include"
            ],
            "defines": [],
            "macFrameworkPath": [
                "/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/System/Library/Frameworks",
                "/System/Library/Frameworks",
                "/Library/Frameworks"
            ],
            "compilerPath": "/usr/bin/clang",
            "cStandard": "c11",
            "cppStandard": "c++17",
            "intelliSenseMode": "${default}"
        }
    ],
    "version": 4
}
           

建立build(連結) task

接下來我們需要建立一個 tasks.json 檔案來告訴 VS Code 怎麼連結(編譯)程式,這個 task 将調用 Clang 編譯器來基于源代碼建立一個可執行檔案.

  1. 從主菜單欄中選擇 View > Command Palette 然後輸入 “task” 選擇

    Tasks: Configure Default Build Task

    . 然後在選擇

    Create tasks.json file from template

    , 之後選擇 Others,VS Code 就會建立一個最小的 tasks.json 檔案并自動打開.
  2. 使用以下代碼段替換掉檔案的整個内容.:
{
    // See https://go.microsoft.com/fwlink/?LinkId=733558
    // for the documentation about the tasks.json format
    "version": "2.0.0",
    "tasks": [
        {
            "label": "Build with Clang",
            "type": "shell",
            "command": "clang++",
            "args": [
                "-std=c++17",
                "-stdlib=libc++",
                "helloworld.cpp",
                "-o",
                "helloworld.out",
                "--debug"
            ],
            "group": {
                "kind": "build",
                "isDefault": true
            }
        }
    ]
}
           

label

是用來在VS Code Command Palette中辨認的一個名字而已; 你可以改成任何你喜歡的名字,這個

args

數組會按編譯器預期的順序傳遞指令行參數.

isDefault": true

當你在按 ⇧⌘B 時會運作該任務.

--debug

參數會生成調試符号,這是調試時單步執行代碼所必需的.

配置調試設定

Next, we’ll configure VS Code to launch the LLDB debugger when you press F5.

  1. From the Command Palette, type “launch” and then choose Debug: Open launch.json. Next, choose the GDB/LLDB environment.
  2. For program, use the program name ${workspaceFolder}/helloworld.out (which matches what you specified in tasks.json).
  3. By default, the C++ extension adds a breakpoint to the first line of main. The stopAtEntry value is set to true to cause the debugger to stop on that breakpoint. You can set this to false if you prefer to ignore it.
  4. Set externalConsole to true to display the program output in an external Terminal window. (Currently on Mac the output cannot be directed to the integrated Terminal window.)

Your complete launch.json file should look something like this:

{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "(lldb) Launch",
            "type": "cppdbg",
            "request": "launch",
            "program": "${workspaceFolder}/helloworld.out",
            "args": [],
            "stopAtEntry": true,
            "cwd": "${workspaceFolder}",
            "environment": [],
            "externalConsole": true,
            "MIMode": "lldb",
            "logging": {
                "trace": true,
                "traceResponse": true,
                "engineLogging": true
            }
        }
    ]
}
           

VS Code is now configured to use Clang on macOS. The configuration applies to the current workspace. To reuse the configuration, just copy the three JSON files to a .vscode folder in a new workspace and change the names of the source file(s) and executable as needed.

The remaining steps are provided as an optional exercise to help you get familiar with the editing and debugging experience.

Add a source code file

  1. In the main VS Code menu, click on File > New File and name it helloworld.cpp.
  2. Paste in this source code:
#include <iostream>
#include <vector>
#include <string>

using namespace std;

int main()
{

    vector<string> msg {"Hello", "C++", "World", "from", "VS Code!"};
    
    for (const string& word : msg)
    {
        cout << word << " ";
    }
    cout << endl;
}
           
  1. Now press ⌘S to save the file. Notice how all the files we have just edited appear in the File Explorer view in the left panel of VS Code:
    mac 使用Clang配置VS Code C/C++環境準備
    This same panel is also used for source control, debugging, searching and replacing text, and managing extensions. The buttons on the left control those views. We’ll look at the Debug View later in this tutorial. You can find out more about the other views in the VS Code documentation.

探索智能提示(IntelliSense)

In your new helloworld.cpp file, hover over vector or string to see type information. After the declaration of the msg variable, start typing msg. as you would when calling a member function. You should immediately see a completion list that shows all the member functions, and a window that shows the type information for the msg object:

mac 使用Clang配置VS Code C/C++環境準備

Build the program

  1. To run the build task that you defined in tasks.json, press ⇧⌘B or from the main menu choose View > Command Palette and start typing “Tasks: Run Build Task”. The option will appear before you finish typing.
  2. When the task starts, you should see an integrated terminal window appear below the code editor. After the task completes, the terminal shows output from the compiler that indicates whether the build succeeded or failed. For a successful Clang build, the output looks something like this:
    mac 使用Clang配置VS Code C/C++環境準備
  3. As the message instructs, press any key to close the integrated terminal.

Start a debugging session

  1. You are now ready to run the program. Press F5 or from the main menu choose Debug > Start Debugging. Before we start stepping through the code, let’s take a moment to notice several changes in the user interface:
  • The Debug Console appears and displays output from the debugger.
  • The code editor highlights the first statement in the main method. This is a breakpoint that the C++ extension automatically sets for you:
    mac 使用Clang配置VS Code C/C++環境準備
  • The workspace pane on the left now shows debugging information. These windows will dynamically update as you step through the code.
    mac 使用Clang配置VS Code C/C++環境準備
  • At the top of the code editor, a debugging control panel appears. You can move this around the screen by grabbing the dots on the left side.
    mac 使用Clang配置VS Code C/C++環境準備

Step through the code

Now we’re ready to start stepping through the code.

  1. Click or press the Step over icon in the debugging control panel.
    mac 使用Clang配置VS Code C/C++環境準備
    This will advance program execution to the first line of the for loop, and skip over all the internal function calls within the vector and string classes that are invoked when the msg variable is created and initialized. Notice the change in the Variables window on the left. In this case, the errors are expected because, although the variable names for the loop are now visible to the debugger, the statement has not executed yet, so there is nothing to read at this point. The contents of msg are visible, however, because that statement has completed.
  2. Press Step over again to advance to the next statement in this program (skipping over all the internal code that is executed to initialize the loop). Now, the Variables window shows information about the loop variables.
  3. Press Step over again to execute the cout statement. Your application is now running in a macOS Terminal window. Press Cmd+Tab to find it. You should see Hello output there on the command line.
  4. If you like, you can keep pressing Step over until all the words in the vector have been printed to the console. But if you are curious, try pressing the Step Into button to step through source code in the C++ standard library!
    mac 使用Clang配置VS Code C/C++環境準備
    To return to your own code, one way is to keep pressing Step over. Another way is to set a breakpoint in your code by switching to the helloworld.cpp tab in the code editor, putting the insertion point somewhere on the cout statement inside the loop, and pressing F9. A red dot appears in the gutter on the left to indicate that a breakpoint has been set on this line.
    mac 使用Clang配置VS Code C/C++環境準備
    Then press F5 to start execution from the current line in the standard library header. Execution will break on cout. If you like, you can press F9 again to toggle off the breakpoint.

Set a watch

Sometimes you might want to keep track of the value of a variable as your program executes. You can do this by setting a watch on the variable.

  1. Place the insertion point inside the loop. In the Watch window, click the plus sign and in the text box, type word, which is the name of the loop variable. Now view the Watch window as you step through the loop.
    mac 使用Clang配置VS Code C/C++環境準備
  2. Add another watch by adding this statement before the loop: int i = 0;. Then, inside the loop, add this statement: ++i;. Now add a watch for i as you did in the previous step.
  3. To quickly view the value of any variable while execution is paused on a breakpoint, you can simply hover over it with the mouse pointer.
    mac 使用Clang配置VS Code C/C++環境準備

原文連結: VS Code C/C++ 配置指南