How to Call libcurl from C on Ubuntu: A Step‑by‑Step Guide

This tutorial walks you through installing libcurl on Ubuntu, writing a simple C program that uses libcurl to perform a GET request, compiling the code with the proper linker flags, and running the executable to display the fetched web page.

Ops Development & AI Practice
Ops Development & AI Practice
Ops Development & AI Practice
How to Call libcurl from C on Ubuntu: A Step‑by‑Step Guide

Prerequisites

Install the libcurl development package on Ubuntu:

sudo apt-get update
sudo apt-get install libcurl4-openssl-dev

Source Code

Create curl_example.c with the following content. The program uses libcurl to perform a simple HTTP GET request and prints the response to standard output.

#include <stdio.h>
#include <curl/curl.h>

size_t write_callback(void *contents, size_t size, size_t nmemb, void *userp) {
    size_t real_size = size * nmemb;
    printf("%s", (char *)contents);
    return real_size;
}

int main(void) {
    CURL *curl;
    CURLcode res;

    curl_global_init(CURL_GLOBAL_ALL);
    curl = curl_easy_init();
    if (curl) {
        curl_easy_setopt(curl, CURLOPT_URL, "http://example.com");
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback);
        res = curl_easy_perform(curl);
        if (res != CURLE_OK) {
            fprintf(stderr, "curl_easy_perform() failed: %s
", curl_easy_strerror(res));
        }
        curl_easy_cleanup(curl);
    }
    curl_global_cleanup();
    return 0;
}

Compilation

Compile and link against libcurl: gcc curl_example.c -o curl_example -lcurl The -lcurl flag tells the linker to use the shared libcurl library, producing the executable curl_example.

Execution

Run the program: ./curl_example The program sends a GET request to http://example.com and prints the returned HTML to the console.

Program output
Program output
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

CompilationCHTTPDynamic LibraryUbuntulibcurl
Ops Development & AI Practice
Written by

Ops Development & AI Practice

DevSecOps engineer sharing experiences and insights on AI, Web3, and Claude code development. Aims to help solve technical challenges, improve development efficiency, and grow through community interaction. Feel free to comment and discuss.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.