Visual Studio Code (VS Code) adalah editor ringan yang dengan ekstensi C/C++ dari Microsoft dapat berfungsi sebagai IDE C lengkap—autocomplete, goto definition, debugging gdb, dan static analysis. Bab ini menuntun kita memasang VS Code, mengonfigurasi ekstensi C/C++, membuat tasks.json untuk build otomatis, dan setup launch.json untuk debugging. Konfigurasi ini bekerja baik di Windows, macOS, maupun Linux.

1. Pemasangan VS Code dan Ekstensi #

Pasang VS Code #

  1. Download installer dari https://code.visualstudio.com/.
  2. Jalankan installer. Untuk Windows, centang opsi Add to PATH agar dapat dipanggil dari terminal.
  3. Buka VS Code.

Pasang Ekstensi C/C++ #

  1. Buka panel Extensions (Ctrl+Shift+X atau Cmd+Shift+X).
  2. Cari C/C++ oleh Microsoft.
  3. Klik Install.
  4. (Opsional) Pasang ekstensi tambahan:
    • C/C++ Extension Pack (bundel beberapa tool)
    • CMake Tools (untuk proyek CMake)
    • clangd (alternatif IntelliSense, lebih akurat di macOS/Linux)

Verifikasi ekstensi terpasang:

bash
code --list-extensions | grep -i "ms-vscode.cpptools"

Output yang Dihasilkan:

2. Membuat dan Membuka Folder Proyek #

VS Code bekerja berbasis folder—konfigurasi disimpan di .vscode/. Buat folder proyek dan buka:

bash
mkdir -p ~/belajar-c/hello
cd ~/belajar-c/hello
code .

Buat file hello.c:

c
/* File: hello.c */
#include <stdio.h>

int main(void) {
    printf("Halo dari VS Code!\n");
    return 0;
}

3. Konfigurasi Build: tasks.json #

VS Code menggunakan tasks.json untuk mengotomatiskan perintah build. Buat file ini di folder .vscode/.

  1. Tekan Ctrl+Shift+P (Cmd+Shift+P di macOS).
  2. Ketik Tasks: Configure Default Build Task.
  3. Pilih C/C++: gcc build active file (atau clang di macOS).

VS Code akan membuat .vscode/tasks.json. Sesuaikan isinya menjadi:

json
{
    "version": "2.0.0",
    "tasks": [
        {
            "label": "Build C",
            "type": "cppbuild",
            "command": "gcc",
            "args": [
                "-std=c11",
                "-Wall",
                "-Wextra",
                "-g",
                "-fdiagnostics-color=always",
                "${file}",
                "-o",
                "${fileDirname}/${fileBasenameNoExtension}"
            ],
            "options": {
                "cwd": "${fileDirname}"
            },
            "problemMatcher": ["$gcc"],
            "group": {
                "kind": "build",
                "isDefault": true
            },
            "detail": "Compiler: gcc"
        }
    ]
}

Untuk macOS dengan Clang, ganti "command": "gcc" menjadi "command": "clang". Untuk MinGW di Windows, tambahkan .exe ke akhir output (otomatis ditambahkan oleh ${fileBasenameNoExtension}).

Untuk menjalankan build: tekan Ctrl+Shift+B (Cmd+Shift+B di macOS). Build berjalan di terminal integrasi VS Code.

Output yang Dihasilkan (di terminal VS Code):

text
> Task - Build C
gcc -std=c11 -Wall -Wextra -g -fdiagnostics-color=always /home/budi/belajar-c/hello/hello.c -o /home/budi/belajar-c/hello/hello

Terminal will be reused by tasks, press any key to close it.

4. Konfigurasi Debug: launch.json #

launch.json mengonfigurasi debugger agar dapat diluncurkan dari VS Code. Buat file ini:

  1. Buka panel Run and Debug (Ctrl+Shift+D).
  2. Klik create a launch.json file.
  3. Pilih C++ (GDB/LLDB) atau C++ (Windows) untuk MinGW.

Sesuaikan .vscode/launch.json:

json
{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Debug C",
            "type": "cppdbg",
            "request": "launch",
            "program": "${fileDirname}/${fileBasenameNoExtension}",
            "args": [],
            "stopAtEntry": false,
            "cwd": "${fileDirname}",
            "environment": [],
            "externalConsole": false,
            "MIMode": "gdb",
            "miDebuggerPath": "/usr/bin/gdb",
            "setupCommands": [
                {
                    "description": "Aktifkan pretty-printing",
                    "text": "-enable-pretty-printing",
                    "ignoreFailures": true
                }
            ]
        }
    ]
}

Untuk macOS, ganti "MIMode": "gdb" menjadi "MIMode": "lldb" dan hapus baris miDebuggerPath (LLDB terintegrasi Xcode Tools).

Untuk Windows MinGW, ganti "miDebuggerPath": "/usr/bin/gdb" menjadi "miDebuggerPath": "C:\\msys64\\ucrt64\\bin\\gdb.exe".

5. Mencoba Debugging #

Tambahkan breakpoint dengan klik di kiri nomor baris di editor VS Code (lingkaran merah muncul). Lalu tekan F5 untuk memulai debugging.

Program berikut cocok untuk mencoba debugging—memiliki loop, kondisional, dan variabel yang dapat kita inspeksi.

c
/* File: debug_demo.c */
#include <stdio.h>

static int faktorial(int n) {
    if (n <= 1) return 1;
    return n * faktorial(n - 1);
}

int main(void) {
    int data[] = {10, 20, 30, 40, 50};
    int total = 0;
    for (int i = 0; i < 5; i++) {
        total += data[i];          /* breakpoint di sini */
    }
    printf("total = %d\n", total);
    printf("5! = %d\n", faktorial(5));
    return 0;
}

Mari kita telaah alur debugging yang diharapkan:

  1. Breakpoint di baris total += data[i]: Saat F5 ditekan, eksekusi berhenti di breakpoint. Panel kiri menampilkan variabel lokal: data, i, total.
  2. Step Over (F10): Klik untuk maju satu baris. Variabel total bertambah, i increment. Kita bisa melihat perubahan setiap iterasi.
  3. Step Into (F11): Saat di baris faktorial(5), klik Step Into untuk masuk ke fungsi faktorial. Stack frame bertambah setiap level rekursi.
  4. Watch: Tambahkan ekspresi n di panel Watch untuk memantau nilai parameter rekursi di setiap frame.
  5. Continue (F5): Lanjutkan eksekusi sampai breakpoint berikutnya atau program selesai.

6. Konfigurasi IntelliSense #

VS Code menyediakan autocomplete via IntelliSense. Untuk akurasi terbaik, buat file .vscode/c_cpp_properties.json:

  1. Tekan Ctrl+Shift+P → C/C++: Edit Configurations (UI).
  2. Pilih Compiler path sesuai sistem (/usr/bin/gcc, /usr/bin/clang, atau C:\msys64\ucrt64\bin\gcc.exe).
  3. Pilih C standard c11 atau c17.
  4. Pilih IntelliSense mode gcc-x64, clang-x64, atau windows-gcc-x64.

File yang dihasilkan kira-kira:

json
{
    "configurations": [
        {
            "name": "Linux",
            "includePath": ["${workspaceFolder}/**"],
            "defines": ["_DEBUG", "UNICODE", "_UNICODE"],
            "cStandard": "c11",
            "intelliSenseMode": "linux-gcc-x64",
            "compilerPath": "/usr/bin/gcc"
        }
    ],
    "version": 4
}

7. Integrasi dengan WSL #

Bila kita bekerja di Windows dengan kode di WSL (lihat bab Setup WSL):

  1. Pasang ekstensi WSL di VS Code Windows.
  2. Buka terminal WSL di folder proyek.
  3. Ketik code . untuk membuka VS Code Windows dengan koneksi ke WSL.
  4. Status bar kiri bawah menampilkan WSL: Ubuntu—artinya editor terkoneksi ke WSL.
  5. tasks.json dan launch.json yang sama dapat dipakai karena compiler adalah GCC Linux native di WSL.

8. Troubleshooting #

Build gagal dengan command 'gcc' not found #

Compiler tidak ada di PATH sistem. Periksa:

bash
which gcc
gcc --version

Bila tidak ditemukan, pasang toolchain (lihat bab Setup Linux / Setup Windows / Setup macOS sesuai OS).

IntelliSense menampilkan garis merah pada #include <stdio.h> #

Path compiler belum dikonfigurasi. Buka C/C++: Edit Configurations (UI) dan set Compiler path dengan path absolut ke compiler.

Debugger gagal start: Cannot read property 'program' #

launch.json tidak ada atau path program salah. Pastikan "program" merujuk ke binary yang sudah di-compile, dan jalankan Build Task (Ctrl+Shift+B) lebih dulu sebelum F5.

Windows: terminal integrasi membuka Command Prompt bukan PowerShell #

Ubah default terminal: Ctrl+Shift+P → Terminal: Select Default Profile → pilih PowerShell atau Git Bash.

macOS: LLDB tidak menampilkan source code #

Tambahkan ke launch.json di bawah setupCommands:

json
{
    "description": "Load source path",
    "text": "settings set target.source-map ${workspaceFolder} ${workspaceFolder}",
    "ignoreFailures": true
}