How to Compile a C Program using libgpio(d) for Raspberry Pi?

Abstract: Resolve compilation errors when building C programs with libgpiod on Raspberry Pi by installing libgpiod-dev and linking with -lgpio.

Created: 2026-08-24 by
Compile a C program using libgpio on Raspberry Pi by linking against the library with the -lgpio flag during compilation. This approach allows your application to interact directly with the hardware GPIO pins, providing low-level control for sensors and actuators without relying on higher-level Python abstractions or system calls.

Prerequisites and Environment Setup

Before compiling any code that interacts with the General Purpose Input/Output (GPIO) pins, you must ensure that your Raspberry Pi environment is properly configured. The primary requirement is having the libgpiod development headers installed. These headers provide the necessary definitions for the compiler to understand the function signatures and data structures used by the library. Without these headers, the compilation process will fail immediately with errors indicating missing header files. You can install the required packages using the standard package manager for Debian-based systems like Raspberry Pi OS. Run the following command in your terminal to update your package lists and install the development libraries:
sudo apt update
sudo apt install libgpiod-dev
This installation provides both the runtime library and the static headers needed for building applications. It is also advisable to have a basic understanding of how the GPIO numbering scheme works on the Raspberry Pi. There are two common numbering schemes: BCM (Broadcom SOC channel numbers) and BOARD (physical pin numbers). Most C libraries, including libgpiod, default to using the BCM numbering scheme because it maps directly to the underlying hardware registers. Ensuring you know which physical pin corresponds to your desired logical channel is critical before writing any code.

Writing the Basic C Code

A typical program using libgpiod involves opening a GPIO line, configuring its direction, and then setting its value. The library uses a descriptor-based model where you first request access to a specific line on a chip. For example, if you want to control an LED connected to GPIO 17, you would need to identify the correct chip index and line number. On most Raspberry Pi models, the main GPIO controller is located at /dev/gpiochip0. The code structure generally follows these steps: include the necessary headers, initialize the context, request the line, set the direction to output, and then toggle the value. Here is a minimal example that sets GPIO 17 high:
#include <stdio.h>
#include <gpiod.h>

int main(void) {
    struct gpiod_chip *chip;
    struct gpiod_line *line;
    int ret;

    // Open the GPIO chip
    chip = gpiod_chip_open_by_name("gpiochip0");
    if (!chip) {
        perror("Failed to open gpiochip0");
        return 1;
    }

    // Request line 17 for output
    line = gpiod_chip_get_line(chip, 17);
    if (!line) {
        perror("Failed to get line 17");
        gpiod_chip_close(chip);
        return 1;
    }

    ret = gpiod_line_request_output(line, "my-led", GPIOD_LINE_ACTIVE_STATE_HIGH);
    if (ret) {
        perror("Failed to request line as output");
        gpiod_chip_close(chip);
        return 1;
    }

    // Set the line high
    ret = gpiod_line_set_value(line, 1);
    if (ret) {
        perror("Failed to set value");
    } else {
        printf("LED turned on successfully.\n");
    }

    // Cleanup
    gpiod_line_release(line);
    gpiod_chip_close(chip);
    return 0;
}
Note that this code requires root privileges to access the GPIO hardware unless appropriate udev rules are in place. In a production environment, you might handle permissions differently, but for testing, running the executable with sudo is standard practice. Always remember to release the line and close the chip descriptor to prevent resource leaks and allow other processes to access the pin.

Compiling the Program

Once your source file, let's call it gpio_example.c, is ready, you need to compile it. The key to successful compilation is linking against the gpiod library. You use the -l flag followed by the library name without the lib prefix or the .so extension. Therefore, the flag is -lgpiod. If the library is not in your standard library path, you may also need to specify the include directory using -I and the library directory using -L. However, on a standard Raspberry Pi OS installation with the dev package installed, the compiler usually finds these automatically. The compilation command looks like this:
gcc gpio_example.c -o gpio_example -lgpiod
After the command executes without errors, an executable file named gpio_example will be created in your current directory. You can verify the binary was created by listing the files or checking its properties. If you encounter undefined reference errors, it typically means the linker cannot find the library. Ensure that libgpiod-dev is installed and that you are spelling the library name correctly. For more complex projects involving multiple source files or external dependencies, consider using a Makefile. A simple Makefile can automate the compilation process and manage dependencies. It ensures that your code is recompiled only when source files change, saving time during development.

Running and Testing

To run the compiled program, execute it from the terminal. Remember that accessing GPIO pins usually requires elevated permissions. Use the following command to run your program:
sudo ./gpio_example
If everything is configured correctly, you should see the message "LED turned on successfully." printed to the console, and the LED connected to GPIO 17 should light up. If the LED does not turn on, check your physical wiring. Verify that the LED is connected to the correct pin and that the ground connection is secure. Also, double-check that you are using the correct GPIO number in your code. The BCM number 17 corresponds to physical pin 11 on the 40-pin GPIO header. It is good practice to test both setting the value to high and low. You can modify the code to toggle the value and observe the behavior. This helps confirm that the library is functioning correctly and that your hardware setup is robust. Additionally, consider adding error handling for edge cases, such as when the GPIO chip is already in use by another process. For users interested in network configuration alongside their hardware projects, understanding connectivity is crucial. If you plan to remote control your GPIO devices, you might encounter networking issues. See How to Fix Issue with Raspberry Pi that Can't Get Out to the Internet After Recent Changes Related to Wireguard/VPN for troubleshooting steps related to VPN interference. Similarly, managing firewall rules is essential for security. Check out Allowing a Device Access to the Internet through UFW on Raspberry Pi to configure your firewall settings properly.

Frequently Asked Questions

Why do I get permission denied errors when running my GPIO program?

Accessing GPIO pins requires root privileges by default on Linux systems. You must run your compiled executable with sudo to bypass these restrictions. Alternatively, you can configure udev rules to grant specific users access to the GPIO device nodes without needing full root access.

Can I use libgpio with older versions of Raspberry Pi OS?

Yes, but compatibility depends on the kernel version. Older kernels may use the legacy sysfs interface instead of libgpiod. It is recommended to use the latest Raspberry Pi OS Bullseye or Bookworm images, which fully support the gpiod API for modern GPIO management.

What is the difference between BCM and BOARD numbering?

BCM numbering refers to the Broadcom SoC channel numbers, which map to the internal hardware registers. BOARD numbering refers to the physical pin numbers on the 40-pin connector. Using BCM is generally preferred in code because it remains consistent regardless of the physical connector layout changes across different Pi models.

How do I debug if my GPIO values are not changing?

First, verify that no other process is holding the GPIO line open. Use tools like lsof to check for conflicting processes. Second, ensure that your code correctly requests the line with the right active state. Finally, check your physical connections and multimeter readings to confirm the hardware is responding to the electrical signals.

Is libgpiod faster than using Python for GPIO control?

Generally, yes. C programs compiled with libgpiod have lower overhead and provide more deterministic timing compared to interpreted Python scripts. This makes C suitable for applications requiring precise timing, such as PWM generation or rapid sensor polling, although Python is easier for quick prototyping.

Latest News

How to Display Output of xterm Command in Terminal Screen using Cron

Resolve the inability to display xterm output in a terminal screen from cron by redirecting logs or using wall instead of insecure X11 workarounds.

Read More
Expose Local Server on VPS Preserving Real Client IPs (OS Level)

Resolve VPS logging showing only gateway IPs by configuring reverse proxies to forward real client addresses via X-Forwarded-For headers.

Read More
How to Clear Recent Files History in Linux without Deleting Actual Files?

Clear recent files history in Linux by deleting ~/.local/share/recently-used.xbel without removing the actual files.

Read More
Best HDD Copy Strategy: Manually Syncing and Rewriting Scratch

Resolve data drift between two 4TB hard drives by using rsync with the --delete flag to manually sync and rewrite scratch data for an exact mirror.

Read More
Understanding Bash Prompt Abbreviations: An Overview

Resolve repetitive typing errors by creating and persisting Bash aliases in the .bashrc file for improved command-line efficiency.

Read More
Free Tools and Methods to Log Real-Time Performance Details in Task Manager

Log real-time CPU and memory metrics to CSV files using Windows Performance Monitor Data Collector Sets to troubleshoot system slowness.

Read More
Contact Qatar Airways Customer Service: Phone Number, Help Center, and More

Resolve urgent Qatar Airways reservation issues like flight changes and baggage claims using the US phone number +1801-855-5905 or online self-service tools.

Read More
Windows 11: Alt Codes Displaying Wrong Characters - Solutions

Resolve Windows 11 Alt codes showing wrong characters by verifying the US keyboard layout and enabling Num Lock.

Read More
Run Programs with Elevated Privileges: A Comprehensive Guide

Eliminates the need to type sudo for frequent administrative tasks by configuring .bashrc aliases or functions.

Read More
Dynamically Changing Dates in Excel Formulas Using Cells

Eliminate manual date updates in Excel by using cell references to create dynamic formulas that automatically adjust calculations when input dates change.

Read More
Granting Edit Access to a Specific Excel Sheet in an Office 365 User Email ID-Based Login

Excel Online lacks native sheet-level permissions, so users must split workbooks or use worksheet protection to isolate edit access for specific tabs.

Read More
Creating Network Load on Local Wi-Fi from One PC

Generate sustained Wi-Fi bandwidth load from a single PC using a VM SFTP server to test router stability and throughput.

Read More
Changing the Default Editor for Batch Files in Windows 11's File Explorer

Resolve the issue of batch files opening in Notepad by changing the default editor to a preferred application like VS Code.

Read More
Gain WiFi Connection Minutes Before Losing it by Changing MAC Address

Bypass MAC address filtering to restore WiFi connectivity temporarily when a device is blocked by network administrators.

Read More
Photos Folders Turned Black: Troubleshooting Picture Applications on Windows

Resolve black screens in Windows Photos by resetting the app, updating graphics drivers, and repairing system files.

Read More
Troubleshooting High CPU Temperature Values: A Step-by-Step Guide

Resolve high CPU temperatures and thermal throttling by monitoring with Speedfan, cleaning dust from cooling components, and replacing degraded thermal paste.

Read More
Make cURL establish TLS connection with CA unknown

Resolve cURL TLS connection failures with unknown or self-signed certificates by using the --insecure flag to bypass CA validation.

Read More
Troubleshooting Incorrect Network Metrics Values in Grafana, Prometheus, InfluxDB, and Telegraf

Fix incorrect network metrics in Grafana, Prometheus, InfluxDB, and Telegraf by verifying interface selection, resolving unit mismatches, and handling counter resets.

Read More
Start Another Terminal Window (cmd.exe) Windows Repair/Troubleshoot

Provides step-by-step instructions to access the Windows Command Prompt via bootable media for advanced system repair and troubleshooting.

Read More
Thinkpad P1 Gen 6: Sudden Thunderbolt 3 Dock USB-C Charging Stopped Working

Resolve sudden Thunderbolt 3 dock USB-C charging and internet failure on ThinkPad P1 Gen 6 by updating firmware, resetting the dock, and adjusting power settings.

Read More
ASUS Windows 11 Laptop: Internet Connection Issue with Hotspot

Resolve ASUS Windows 11 laptop spinning wheel issue when connecting to mobile hotspot by resetting network stack, disabling IPv6, and adjusting power settings.

Read More
Developing iOS Project with Firebase: Logging in and Sending Push Notifications

Integrates Firebase to enable secure user authentication and push notifications in iOS applications.

Read More
Troubleshooting Bash Script with Suspected Issues of Spaces, Dashes, Filenames and Quoting

Resolve Bash script failures caused by word splitting, globbing, and special characters in filenames by applying proper quoting techniques.

Read More
Populating OneDrive Folder for Local Backup without Affecting Remote Files

Prevent OneDrive from deleting remote files during Windows reinstallation by unlinking the account or using symbolic links to isolate local data.

Read More
Force First Frame as Keyframe Without Re-encoding: A Quick Solution

Resolve inaccurate seeking and playback glitches by re-encoding video to ensure the first frame is a valid keyframe.

Read More
Find Information in Database Using WSL (Ubuntu) on Windows-10

Resolve database connection issues from WSL Ubuntu on Windows 10 by configuring client tools and network access to query remote or local servers.

Read More
Configuring a New Router with Different Networks: One Family, One Guest

Resolve IP conflicts and isolate guest traffic by configuring a second router with a distinct subnet via its WAN port.

Read More
Quickly Open Multiple Stock Websites with a Single Command

Solve the problem of manually opening multiple stock research websites by creating a single command to launch them simultaneously on Windows, macOS, or Linux.

Read More
Improved Adobe Acrobat Search Experience: Access Advanced Search with Ease

Access advanced search filters like case sensitivity and regex in Adobe Acrobat by clicking More Options in the Find bar.

Read More
Port Forwarding VM via OpenVPN: A Comprehensive Guide

Configure OpenVPN server and iptables to forward specific ports from VPN clients to a virtual machine's internal IP address.

Read More
Understanding Partitions in the 1980s: A Look Back at MS-DOS and Master Boot Record

Explains how the Master Boot Record and partition table enabled MS-DOS to manage multiple disk volumes on a single physical drive.

Read More
Windows 10 Enterprise: Keyboard Not Detected in Managed Organization with Admin Privileges

Resolve Windows 10 Enterprise keyboard detection failures caused by Group Policy restrictions, driver corruption, or USB enumeration errors.

Read More
Can't Find x86_64 Versions of Applications on MacOS arm64 (M1)

Resolve missing x86_64 app issues on M1 Macs by installing Rosetta 2 and reinstalling apps as universal binaries.

Read More
How to Hide Installation Source for an Android App

Manage Android app installation source visibility by using USB transfers or file managers to reduce browser traces and isolate data via work profiles.

Read More
Connecting Momentus 4200.2 ST9808210A Hard Drive via USB Cable

Resolve inability to access Seagate Momentus 4200.2 ST9808210A hard drive by connecting it via USB using a compatible SATA-to-USB adapter and configuring the disk in Windows.

Read More