簡體   English   中英

在 Mac 上使用 Visual Studio Code 運行 C++ 程序

[英]Running a C++ Program on Mac in Visual Studio Code

我正在嘗試運行:

    #include <iostream>

int main() {
    std::cout << "Hello World!";
    return 0;
}

在我的 Mac 上。 我在 Visual Studio Code 中安裝了 C++ 和 Code Runner。 但我收到以下錯誤:

[Running] cd "/Users/NAME/Documents/Program/C++/" && g++ test.cpp -o test && "/Users/NAME/Documents/Program/C++/"test Undefined symbols for architecture x86_64:   "_main", referenced from:
     implicit entry/start for main executable ld: symbol(s) not found for architecture x86_64 clang: error: linker command failed with exit code 1 (use -v to see invocation)

[Done] exited with code=1 in 0.081 seconds

要構建和運行 helloWorld.cpp 或任何其他項目,您需要先創建構建設置。

考慮到您已經創建了helloworld.cpp文件,請按照以下步驟操作:

  1. 您將創建一個 tasks.json 文件來告訴 VS Code 如何構建(編譯)程序。 此任務將調用 Clang C++(或 g++,如果您想使用 gcc 構建)編譯器從源代碼創建一個可執行文件。
  2. 在編輯器中打開 helloworld.cpp 很重要,因為下一步使用編輯器中的活動文件作為上下文來創建下一步中的構建任務。
  3. 從主菜單中,選擇終端 > 配置默認構建任務。 將出現一個下拉列表,其中列出了 VS Code 在您的機器上找到的編譯器的各種預定義構建任務。 選擇C/C++ clang++ build active file (或者 g++ 如果你想用 gcc 構建)來構建當前在編輯器中顯示(活動)的文件。
  4. 這將在 .vscode 文件夾中創建一個 tasks.json 文件並在編輯器中打開它。

例如,我的tasks.json看起來像這樣(我使用了 g++)

{
    // See https://go.microsoft.com/fwlink/?LinkId=733558 
    // for the documentation about the tasks.json format
    "version": "2.0.0",
    "tasks": [
        {
            "type": "shell",
            "label": "g++ build active file",
            "command": "/usr/bin/g++",
            "args": [
                "-std=c++17",
                "-stdlib=libc++",
                "-g",
                "${file}",
                "-o",
                "${fileDirname}/${fileBasenameNoExtension}"
            ],
            "options": {
                "cwd": "${workspaceFolder}"
            },
            "problemMatcher": [
                "$gcc"
            ],
            "group": {
                "kind": "build",
                "isDefault": true
            }
        }
    ]
}
  1. 回到helloworld.cpp 因為我們要構建helloworld.cpp所以這個文件是下一步在編輯器中處於活動狀態的文件是很重要的。
  2. 要運行您在tasks.json定義的構建任務,請按 ⇧⌘B 或從終端主菜單中選擇運行構建任務。
  3. 使用 + 按鈕創建一個新終端,您將擁有一個以 helloworld 文件夾作為工作目錄的新終端。 運行 ls,您現在應該會看到可執行文件 helloworld 以及調試文件 (helloworld.dSYM)。
  4. 您可以在終端中輸入 ./helloworld 來運行 helloworld

注意:這是您在此處的官方文檔中看到的內容的簡短概述。 您可以用 gcc 替換 clang 以使用 gcc 進行編譯和構建。

終端輸出:

  • 叮當++
xecuting task: /usr/bin/clang++ -std=c++17 -stdlib=libc++ -g /Users/Projects/test/helloworld.cpp -o /Users/Projects/test/helloworld <
  • 加++
Executing task: /usr/bin/g++ -std=c++17 -stdlib=libc++ -g /Users/Projects/test/helloworld.cpp -o /Users/Projects/test/helloworld <

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM