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.
Prerequisites
Install the libcurl development package on Ubuntu:
sudo apt-get update
sudo apt-get install libcurl4-openssl-devSource 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.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
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.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
