WSL2とVSCodeを使ってC/C++ビルド環境を整える

Windows10で、VSCodeを使ったC言語の開発環境を作りました。
MinGWを使わず、WSL2のubuntu内にあるコンパイラを使う環境を今回作りました。

Goal

Hardware

Windows PC

Software

  • OS : Windows 10 build ver.2004
  • Editor : VSCode
  • Virtual platform : WSL2
  • Virtual OS : Ubuntu 20.04 LTD

References

docs.microsoft.com
qiita.com
qiita.com
ntk-ta01.hatenablog.com


上記の参考サイトを見ても、環境構築、Cソースのビルド動作を確認できない場合は、続きを参考にしてください。

手順

  1. (Windows10) VSCode install
  2. (Windows10) WSL2 install
    • (Windows10) WSL 2 Linux カーネルの更新
    • (Windows10) WSLのバージョンとして2を標準として設定
 wsl --set-default-version 2
  1. (Windows10) ディストリビューションのインストール
  2. (WSL2)gccubuntuにインストール
sudo apt update
sudo apt install build-essential
  1. (VSCODE) Remote - WSLのインストール
  2. VSCodeソースコードを置くフォルダを開く
  3. VSCodeでフォルダ内にソースコード(main.c)を作成する
  4. RemoteExplorerでubuntu20.04に接続し、main.cを開く
    • Ctl + Shift + Pでコマンドパレットを開き、「reopen Folder in WSL」を実行する
    • 又は、WSLのターミナル上で、" code ."と入力する
  5. コマンドパレットでC/C++ Edit configurations(JSON) の変更を開く
{
    "configurations": [
        {
            "name": "Linux",
            "includePath": [
                "${workspaceFolder}/**",
                "/usr/include/**",
            ],
            "defines": [],
            "compilerPath": "/usr/bin/gcc",
            "cStandard": "c11",
            "cppStandard": "c++17",
            "intelliSenseMode": "gcc-x64"
        }
    ],
    "version": 4
}
  1. コマンドパレットでTasks: Configure Default Build taskを開く
  2. gcc build active fileを選択する
{
    // See https://go.microsoft.com/fwlink/?LinkId=733558
    // for the documentation about the tasks.json format
    "version": "2.0.0",
    "tasks": [
        {
            "label": "build",
            "type": "shell",
            "options": {
                "shell": {
                    "executable": "C:\\Windows\\System32\\wsl.exe"
                }
            },
            "command": "g++",
            "args": [
                "-std=gnu++1y",
                "-g",
                "-O0",
                "-I/opt/boost/gcc/include",
                "-L/opt/boost/gcc/lib",
                "-o",
                "`wslpath",
                "'${workspaceFolder}\\output.exe'`",
                "`wslpath",
                "'${file}'`"
            ],
            "group": "build",
            "problemMatcher": []
        },
        {
            "type": "cppbuild",
            "label": "C/C++: gcc build active file",
            "command": "/usr/bin/gcc",
            "args": [
                "-g",
                "${file}",
                "-o",
                "${fileDirname}/${fileBasenameNoExtension}"
            ],
            "options": {
                "cwd": "${workspaceFolder}"
            },
            "problemMatcher": [
                "$gcc"
            ],
            "group": {
                "kind": "build",
                "isDefault": true
            },
            "detail": "compiler: /usr/bin/gcc"
        }
    ]
}
  1. ソースコードを書く
    • 例) main.c
#include <stdio.h>

int main(int argc, char **argv){
    printf("Hello World!\n");
    return 0;
}
    • この時点で、#include に参照エラーが出力されている場合、WSL上でソースコードを編集できていない可能性があります
      • C:\Users\ ... \AppData\Local\Packages\CanonicalGroupLimited.Ubuntu onWindows ... \LocalState\rootfs\usr\include" が見つかりません
      • C:\Users\ ... \AppData\Local\Packages\CanonicalGroupLimited.Ubuntuext4.vhdxがある
  1. Ctl+Shift + B でビルド開始
> Executing task: C/C++: gcc build active file <

Starting build...
Build finished successfully.

Terminal will be reused by tasks, press any key to close it.
  1. Ctl + Shift + @ でターミナルを開き、ビルドデータの確認をする
    • mainという実行ファイルが生成されている
  2. ビルドデータを実行する
    • ./main
  1. ビルドデータのデバッグをする際は、.vscode/launch.jsonを記述する
{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "name": "gcc - Build and debug active file",
            "type": "cppdbg",
            "request": "launch",
            "program": "${fileDirname}/${fileBasenameNoExtension}",
            "args": [],
            "stopAtEntry": false,
            "cwd": "${fileDirname}",
            "environment": [],
            "externalConsole": false,
            "MIMode": "gdb",
            "setupCommands": [
                {
                    "description": "Enable pretty-printing for gdb",
                    "text": "-enable-pretty-printing",
                    "ignoreFailures": true
                }
            ],
            "preLaunchTask": "C/C++: gcc build active file",
            "miDebuggerPath": "/usr/bin/gdb"
        }
    ]
}