Skip to content

Complete setup guide for C/C++ development on Arch Linux with VS Code - includes compiler installation, extensions, debugging, and CMake configuration.

Notifications You must be signed in to change notification settings

YUVARAJ-R-ai/Arch-linux-C-C-setup

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

2 Commits
Β 
Β 

Repository files navigation

πŸš€ C/C++ Development Environment on Arch Linux with VS Code

Welcome! This guide provides comprehensive, step-by-step instructions to set up a robust C and C++ development environment on Arch Linux using Visual Studio Code. It covers installing necessary system dependencies, configuring VS Code with essential extensions, and setting up build/debug tasks for a smooth workflow.

🎯 Target Audience: Users of Arch Linux (or Arch-based distributions) looking to develop C/C++ applications with VS Code.


πŸ“‹ Table of Contents


Prerequisites

Before starting, ensure you have:

  • βœ… A working Arch Linux installation (or an Arch-based distribution)
  • βœ… An active internet connection
  • βœ… Basic familiarity with the Linux terminal and the pacman package manager
  • βœ… An AUR (Arch User Repository) helper like yay or paru (highly recommended)

Installing an AUR Helper (if needed)

If you don't have an AUR helper, here's how to install yay:

sudo pacman -S --needed git base-devel
git clone https://aur.archlinux.org/yay.git
cd yay
makepkg -si
cd .. && rm -rf yay  # Optional: clean up

Phase 1: Install System Dependencies πŸ“¦

These are the fundamental compilers, build tools, and debuggers needed system-wide.

1.1. Update System

Always begin by ensuring your system is fully up-to-date:

sudo pacman -Syu

1.2. Core Build Tools (GCC, G++, Make)

The base-devel group installs essential tools for compiling software, including:

  • GCC (GNU C Compiler)
  • G++ (GNU C++ Compiler)
  • make
  • binutils
sudo pacman -S --needed base-devel

1.3. Clang Compiler & Tools (Recommended)

Clang is an alternative C/C++/Objective-C compiler from the LLVM project. It's known for faster compilation and more precise error messages.

This package also includes:

  • clangd: A powerful Language Server Protocol (LSP) server for C/C++
  • clang-format: A code formatter
  • clang-tidy: A C++ linter and static analyzer
sudo pacman -S --needed clang

1.4. Build Systems (CMake, Meson)

CMake: A widely used, cross-platform build system generator.

sudo pacman -S --needed cmake

Meson (Optional): Another modern and fast build system gaining popularity.

sudo pacman -S --needed meson

Note: make is already installed via base-devel

1.5. Debuggers (GDB, LLDB)

GDB (GNU Debugger): The standard debugger for GCC/G++.

sudo pacman -S --needed gdb

LLDB (LLVM Debugger): The standard debugger for Clang/Clang++.

sudo pacman -S --needed lldb

1.6. Version Control (Git)

Essential for almost any software development workflow.

sudo pacman -S --needed git

Phase 2: Install Visual Studio Code πŸ’»

For the most seamless experience with extensions (especially proprietary ones) and to avoid potential signature verification issues, it's recommended to install the official Microsoft-branded build from the AUR.

Using your preferred AUR helper (e.g., yay):

yay -S visual-studio-code-bin

πŸ’‘ Tip: If you strictly prefer the fully open-source build from Arch's official repositories, you can install code (sudo pacman -S code). However, you might occasionally encounter issues installing certain extensions from the Microsoft Marketplace.


Phase 3: Essential VS Code Extensions 🧩

Open VS Code, then press Ctrl+Shift+X to open the Extensions view and install the following:

1. C/C++ by Microsoft (ms-vscode.cpptools)

Provides core C/C++ language support, debugging capabilities, and basic IntelliSense.

2. clangd by LLVM Team (llvm-vs-code-extensions.vscode-clangd)

🌟 Highly Recommended! Offers superior IntelliSense features (autocompletion, diagnostics, go-to-definition, etc.) by leveraging the clangd LSP server installed earlier.

⚠️ Important: After installing clangd, you might want to disable the default IntelliSense engine from the Microsoft C/C++ extension to prevent conflicts.

Open VS Code settings (Ctrl+,), search for C_Cpp.intelliSenseEngine, and set it to Disabled. clangd will then take over.

3. CodeLLDB by Vadim Chugunov (vadimcn.vscode-lldb)

Essential if you plan to use Clang and LLDB for debugging. This extension integrates LLDB seamlessly into VS Code's debugging interface.

4. CMake Tools by Microsoft (ms-vscode.cmake-tools)

Indispensable if you use CMake for your projects. It provides excellent integration for configuring, building, and debugging CMake-based applications directly within VS Code.


Phase 4: Configure VS Code for C/C++ βš™οΈ

For each C/C++ project (folder) you open in VS Code, you'll typically create a .vscode subdirectory containing configuration files.

4.1. Workspace Setup

  1. Open VS Code
  2. Go to File > Open Folder... (or Ctrl+K Ctrl+O) and select your project's root directory
  3. If prompted about "Restricted Mode," and you trust the folder's contents, click "Trust folder and enable all features"
  4. VS Code will automatically create a .vscode folder in your project directory when you start configuring tasks or launch settings

4.2. IntelliSense Configuration (.vscode/c_cpp_properties.json)

This file helps the C/C++ extension (and clangd if a compile_commands.json is not found) understand your project structure, include paths, and compiler settings for IntelliSense.

  1. Press Ctrl+Shift+P to open the Command Palette
  2. Type C/C++: Edit Configurations (UI) or C/C++: Edit Configurations (JSON)
  3. A c_cpp_properties.json file will be created (or opened) in the .vscode folder

Example c_cpp_properties.json:

{
    "configurations": [
        {
            "name": "Linux",
            "includePath": [
                "${workspaceFolder}/**"
                // Add other library include paths here, e.g., "/usr/include/your_library"
            ],
            "defines": [],
            "compilerPath": "/usr/bin/g++", // Or /usr/bin/clang++
            "cStandard": "c17",
            "cppStandard": "c++17", // Or c++14, c++20, etc.
            "intelliSenseMode": "linux-gcc-x64" // Or "linux-clang-x64" if using clang
        }
    ],
    "version": 4
}

πŸ’‘ Note for clangd users: clangd primarily relies on a compile_commands.json file for the most accurate IntelliSense. This file is usually generated by build systems like CMake or Meson (see Phase 6). If compile_commands.json exists in your workspace or build directory, clangd will use it automatically, making c_cpp_properties.json less critical for clangd's core functionality.

4.3. Build Task Configuration (.vscode/tasks.json)

This file defines how VS Code should compile your C/C++ code.

  1. Press Ctrl+Shift+P, type Tasks: Configure Default Build Task
  2. Select "Create tasks.json file from template", then choose "Others" (or a C++ compiler option like "g++ build active file" if available)

Example tasks.json for G++ (building the active file):

{
    "version": "2.0.0",
    "tasks": [
        {
            "label": "C/C++: g++ build active file", // Referenced by launch.json preLaunchTask
            "type": "shell", // Or "cppbuild" (C/C++ extension's task type)
            "command": "/usr/bin/g++",
            "args": [
                "-fdiagnostics-color=always", // Enables colored compiler output
                "-g",                         // Includes debug symbols
                "${file}",                    // Compiles the currently active file
                "-o",
                "${fileDirname}/${fileBasenameNoExtension}", // Output executable name and location
                "-std=c++17"                  // Specify C++ standard (e.g., c++14, c++20)
                // For multi-file projects, list all .cpp files or use wildcards:
                // "${workspaceFolder}/*.cpp",
                // "-o", "${workspaceFolder}/my_program_name"
            ],
            "options": {
                "cwd": "${workspaceFolder}" // Sets current working directory for the build
            },
            "problemMatcher": [
                "$gcc"                        // Helps VS Code parse compiler errors/warnings
            ],
            "group": {
                "kind": "build",
                "isDefault": true             // Makes this the default build task (Ctrl+Shift+B)
            },
            "detail": "Compiler: /usr/bin/g++"
        }
        // You can add more tasks, e.g., for Clang++ or specific project targets
    ]
}

To build: Press Ctrl+Shift+B (runs the default build task) or open the Command Palette (Ctrl+Shift+P) and type Tasks: Run Build Task, then select your desired task.

4.4. Debug Configuration (.vscode/launch.json)

This file tells VS Code how to run and debug your compiled program.

  1. Navigate to the "Run and Debug" view (icon on the sidebar or Ctrl+Shift+D)
  2. If no launch.json exists, click "create a launch.json file"
  3. Select your environment:
    • "C++ (GDB/LLDB)" (usually the best starting point)
    • Or a more specific "C/C++: (gdb) Launch" or "C/C++: (lldb) Launch"

Example launch.json for GDB:

{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "(gdb) Launch C++ Program", // Descriptive name for the debug configuration
            "type": "cppdbg", // Debugger type for Microsoft C/C++ extension
            "request": "launch", // We want to launch a new process
            "program": "${fileDirname}/${fileBasenameNoExtension}", // Path to your executable
            // If building a fixed executable name: "program": "${workspaceFolder}/my_program_name",
            "args": [], // Command line arguments to pass to your program
            "stopAtEntry": false, // Set to true to automatically stop at the beginning of main()
            "cwd": "${workspaceFolder}", // Current working directory for your program
            "environment": [],
            "externalConsole": false, // false = use VS Code's integrated terminal/debug console
            "MIMode": "gdb",
            "miDebuggerPath": "/usr/bin/gdb", // Path to your GDB executable
            "setupCommands": [
                {
                    "description": "Enable pretty-printing for gdb",
                    "text": "-enable-pretty-printing",
                    "ignoreFailures": true
                }
            ],
            "preLaunchTask": "C/C++: g++ build active file" // CRITICAL: Must match a 'label' in tasks.json
        }
        // You can add other configurations, e.g., for LLDB or attaching to a running process
    ]
}

To debug: Open the C/C++ source file, set breakpoints by clicking in the gutter to the left of the line numbers, then press F5 or click the green play button (Start Debugging) in the "Run and Debug" view.


Phase 5: Test Your Setup βœ…

Let's verify everything is working with a small example.

  1. Create a new folder for your test project, e.g., my_cpp_test_project
  2. Open this folder in VS Code (File > Open Folder...)
  3. Create a simple C++ file, e.g., hello.cpp:
#include <iostream>
#include <vector>
#include <string>

int main() {
    std::vector<std::string> msg {"Hello", "C++", "World", "from", "Arch Linux", "and", "VS Code!"};
    for (const std::string& word : msg) {
        std::cout << word << " ";
    }
    std::cout << std::endl;
    std::cout << "Testing complete!" << std::endl;
    return 0;
}
  1. Configure tasks.json and launch.json as described in Phase 4 within the .vscode folder of this test project
  2. Ensure the "label" in tasks.json matches the "preLaunchTask" in launch.json
  3. Ensure the "program" path in launch.json correctly points to the output executable defined in tasks.json

Testing Steps:

  • Build: Press Ctrl+Shift+B. Check the TERMINAL panel for compiler output and success messages
  • Debug: Press F5. Execution should stop at any breakpoints you've set. You can inspect variables in the DEBUG CONSOLE or the "Variables" section of the Run and Debug view. Program output will typically appear in the TERMINAL or DEBUG CONSOLE

Phase 6: Using CMake πŸ—οΈ

For projects with multiple files, external dependencies, or complex build requirements, CMake is a powerful and widely adopted solution.

Prerequisites

  • Ensure you have the CMake Tools extension (ms-vscode.cmake-tools) installed in VS Code

Setup

  1. Create a CMakeLists.txt file in your project's root directory

Example CMakeLists.txt:

cmake_minimum_required(VERSION 3.10) # Specify minimum CMake version
project(MyAwesomeProject CXX)       # Project name and language (CXX for C++, C for C)

# Set C++ standard (e.g., 14, 17, 20)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED True)

# Generate compile_commands.json for tools like clangd
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)

# Add your source files to create an executable
add_executable(MyAwesomeProject_run # Name of your executable
    src/main.cpp
    src/utils.cpp
    # Add more .cpp files here
)

# Example for including header directories
# target_include_directories(MyAwesomeProject_run PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include)

# Example for linking an external library (if needed)
# find_package(MyLibrary REQUIRED)
# target_link_libraries(MyAwesomeProject_run PRIVATE MyLibrary::MyLib)

Using CMake Tools in VS Code

When you open a folder containing a CMakeLists.txt file, the CMake Tools extension will typically prompt you to configure the project.

Key Features:

  • Select Kit: Choose your compiler toolchain (e.g., GCC or Clang)
  • Select Variant: Choose the build type (e.g., Debug, Release, RelWithDebInfo)
  • Build Target: Click the [Build] button (or press F7) to build the default target
  • Launch Target: Choose the executable target you want to run or debug
  • Debug/Run: Click the play/bug icons in the status bar (or use F5 for Debug / Ctrl+F5 for Run Without Debugging)

πŸ’‘ Note: CMake Tools automatically generates a compile_commands.json file in your build directory (e.g., build/compile_commands.json). clangd will use this file for highly accurate IntelliSense.


Optional Enhancements ✨

7.1. Code Formatting (clang-format)

clang-format (installed as part of the clang package) can automatically format your code according to a defined style.

  1. Create a .clang-format file in your project root to specify your coding style. You can base it on predefined styles (LLVM, Google, Mozilla, WebKit) or customize it fully
  2. Example: clang-format -style=llvm -dump-config > .clang-format to get a starting point

Configure VS Code to format on save:

  1. Open settings (Ctrl+,), search for "Format On Save" and enable it
  2. Search for "Default Formatter" and ensure "C/C++" is set to use clang-format (the C/C++ extension usually picks it up if clang-format is in your PATH)

You might need to set C_Cpp.clang_format_path explicitly if VS Code can't find it.

7.2. Static Analysis (clang-tidy)

clang-tidy (also part of the clang package) is a powerful linter and static analyzer that can help find subtle bugs, style issues, and potential performance problems.

  • It can be configured using a .clang-tidy file in your project root
  • The clangd VS Code extension can integrate clang-tidy checks and display diagnostics directly in the editor

7.3. Wayland Considerations for VS Code

VS Code is an Electron application. While it generally works well on Wayland (often via XWayland by default), you can try enabling native Wayland rendering for potentially better scaling and sharpness, especially on HiDPI displays.

Launch VS Code from the terminal with specific flags:

code --enable-features=UseOzonePlatform --ozone-platform=wayland

πŸ’‘ Note: Recent versions of VS Code have improved Wayland detection and may use it automatically if your environment is suitable.


Troubleshooting πŸ›

"Compiler not found" / "g++: command not found" / "clang++: command not found"

  • Ensure base-devel (for GCC/G++) and/or clang are correctly installed (see Phase 1)
  • Verify that your system's PATH environment variable includes the directory where compilers are installed (usually /usr/bin)

"Could not find the task '...'" (error when trying to build/debug)

  • Double-check that the preLaunchTask value in your .vscode/launch.json exactly matches a "label" of a task defined in your .vscode/tasks.json file
  • Ensure your tasks.json is correctly formatted (valid JSON) and saved in the .vscode folder

IntelliSense Not Working or Incorrect

If using clangd:

  • Ensure clangd is installed and the clangd VS Code extension is enabled
  • For CMake/Meson projects, make sure a compile_commands.json file is generated in your build directory and that clangd can find it (CMake Tools usually handles this)
  • Try restarting the clangd language server: Ctrl+Shift+P > clangd: Restart language server

If using Microsoft C/C++ IntelliSense (and clangd is disabled):

  • Verify the settings in .vscode/c_cpp_properties.json (especially compilerPath, includePath, and intelliSenseMode)
  • Try restarting the IntelliSense server: Ctrl+Shift+P > C/C++: Restart IntelliSense Server

Errors during package installation (e.g., 404 errors from Chaotic-AUR)

  • Run sudo pacman -Syyu to force a refresh of all package lists from your configured repositories
  • Repository mirrors might be temporarily down or out of sync. Try the installation again after some time
  • Check the status or forums for the specific repository (e.g., Chaotic-AUR) if problems persist

Contributing ❀️

Your contributions to improve this guide are highly welcome! If you find any errors, have suggestions for improvements, or want to add more useful information, please feel free to:

  • πŸ› Open an Issue to discuss changes
  • πŸ”§ Submit a Pull Request with your proposed enhancements

License πŸ“œ

This documentation is made available under the MIT License.


Happy Coding on Arch Linux! πŸ§πŸ’»

Made with ❀️ for the Arch Linux community

About

Complete setup guide for C/C++ development on Arch Linux with VS Code - includes compiler installation, extensions, debugging, and CMake configuration.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published