I recommend seeing first – installation of Homebrew and asdf on Ubuntu (it’s short, only 5 commands)
📘 Official Documentation
C++ - Reference on CPPReference
C++ - On DevDocs.io
⭐ Popular Frameworks (ordered from lower to higher learning curve)
⚠️ In C++ there are no standard “web frameworks” like in Python, but there are widely used libraries.
- No Framework (POSIX sockets) — Minimalist, simple, native.
- Crow — Inspired by Flask, very easy to use.
- Boost.Beast — Fast and modern for HTTP/WebSocket.
- CppRestSDK — Complete, Django/Express style.
🛠️ C++ Installation on Ubuntu
C++ already comes installed, but you should make sure you have g++:
sudo apt update
sudo apt install g++ build-essential
🍺 Installation with Homebrew
brew install gcc
📦 Standard Package Manager
C++ does not have an official manager like pip or npm, but the most used ones are:
- apt (on Ubuntu)
- vcpkg
- conan
Check compiler version:
g++ --version
Install a JSON library (example):
sudo apt install nlohmann-json3-dev
🔧 Installation with ASDF
ASDF can compile specific versions of GCC/LLVM.
System dependencies:
sudo apt update
sudo apt install -y build-essential libssl-dev zlib1g-dev \
libbz2-dev libreadline-dev libsqlite3-dev wget curl llvm \
libncursesw5-dev xz-utils tk-dev libxml2-dev libxmlsec1-dev
Install plugin + version
asdf plugin add gcc
asdf install gcc 14.1.0
asdf global gcc 14.1.0
Example: .tool-versions
gcc 14.1.0
📝▶️ Create and run a C++ file
Create file:
touch hello.cpp
Contents of hello.cpp
#include <iostream>
int main() {
std::cout << "Hola Mundo desde C++!\n";
return 0;
}
💻 Compile and run locally:
g++ hello.cpp -o app-hello
./app-hello
🟦 Basic example in C++
🗂️🌐 Static file Web Server.
Note: C++ does not come with an integrated web server.
But you can create a very small one using POSIX sockets (no dependencies).
📝 Create file: touch server.cpp
📦 Contents of server.cpp
#include <iostream>
#include <string>
#include <regex>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
std::string html_escape(const std::string& text) {
std::string escaped = text;
escaped = std::regex_replace(escaped, std::regex("&"), "&");
escaped = std::regex_replace(escaped, std::regex("<"), "<");
escaped = std::regex_replace(escaped, std::regex(">"), ">");
escaped = std::regex_replace(escaped, std::regex("\""), """);
return escaped;
}
int main() {
int server = socket(AF_INET, SOCK_STREAM, 0);
sockaddr_in addr{};
addr.sin_family = AF_INET;
addr.sin_port = htons(8000);
addr.sin_addr.s_addr = INADDR_ANY;
bind(server, (sockaddr*)&addr, sizeof(addr));
listen(server, 10);
std::cout << "Server running at http://localhost:8000\n";
while (true) {
int client = accept(server, nullptr, nullptr);
char buffer[2048] = {0};
read(client, buffer, sizeof(buffer));
std::string request(buffer);
// Extract path
size_t start = request.find("GET ");
size_t end = request.find(" HTTP/");
std::string path = request.substr(start + 4, end - (start + 4));
// Get username
std::string username = "guest";
size_t qpos = path.find("?username=");
if (qpos != std::string::npos) {
username = path.substr(qpos + 10);
}
username = html_escape(username);
// Generate HTML
std::string content =
"<!DOCTYPE html><html lang='es'><head><meta charset='UTF-8'>"
"<title>Hello</title></head><body style='text-align:center'>"
"<h1>Hello, " + username + "</h1></body></html>";
std::string response =
"HTTP/1.1 200 OK\r\n"
"Content-Type: text/html\r\n"
"Content-Length: " + std::to_string(content.size()) + "\r\n"
"Connection: close\r\n\r\n" +
content;
send(client, response.c_str(), response.size(), 0);
close(client);
}
}
▶️ Compile and run
g++ server.cpp -o http-server
./http-server
👉 Visit:
http://localhost:8000/?username=Homero
⚙️🧩 JSON REST API
What it does:
- Reads data from a
data.jsonfile - Exposes two endpoints:
- List of characters at
/characters - Data by ID at
/characters/:id
Example file: data.json
[
{
"id": 1,
"age": 39,
"name": "Homer Tompson",
"portrait_path": "https://cdn.thesimpsonsapi.com/500/character/1.webp"
},
{
"id": 2,
"age": 39,
"name": "Marge Simpson",
"portrait_path": "https://cdn.thesimpsonsapi.com/500/character/2.webp"
}
]
📝 Create file: touch api.cpp
▶️ File contents: api.cpp
This example uses the nlohmann/json library (header-only).
Install it on Ubuntu:
sudo apt install nlohmann-json3-dev
#include <iostream>
#include <fstream>
#include <string>
#include <regex>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
// Load JSON file
json load_characters() {
std::ifstream f("data.json");
json data;
f >> data;
return data;
}
std::string make_json_response(const json& data, int status=200) {
std::string body = data.dump();
return
"HTTP/1.1 " + std::to_string(status) + " OK\r\n"
"Content-Type: application/json\r\n"
"Content-Length: " + std::to_string(body.size()) + "\r\n"
"Connection: close\r\n\r\n" +
body;
}
int main() {
int server = socket(AF_INET, SOCK_STREAM, 0);
sockaddr_in addr{};
addr.sin_family = AF_INET;
addr.sin_port = htons(7001);
addr.sin_addr.s_addr = INADDR_ANY;
bind(server, (sockaddr*)&addr, sizeof(addr));
listen(server, 10);
std::cout << "Server running at http://localhost:7001/characters\n";
while (true) {
int client = accept(server, nullptr, nullptr);
char buffer[4096] = {0};
read(client, buffer, sizeof(buffer));
std::string request(buffer);
size_t s = request.find("GET ");
size_t e = request.find(" HTTP/");
std::string path = request.substr(s + 4, e - (s + 4));
json data = load_characters();
// /characters
if (path == "/characters") {
auto res = make_json_response(data, 200);
send(client, res.c_str(), res.size(), 0);
close(client);
continue;
}
// /characters/:id
std::regex reg("^/characters/([0-9]+)$");
std::smatch match;
if (std::regex_match(path, match, reg)) {
int id = std::stoi(match[1]);
json found = nullptr;
for (auto& c : data)
if (c["id"] == id) found = c;
if (!found.is_null()) {
auto res = make_json_response(found, 200);
send(client, res.c_str(), res.size(), 0);
} else {
auto res = make_json_response({{"error","Character not found"}}, 404);
send(client, res.c_str(), res.size(), 0);
}
close(client);
continue;
}
// Route not found
json notfound = {
{"error", "Route not found"},
{"url_list", "http://localhost:7001/characters"},
{"url_character", "http://localhost:7001/characters/1"}
};
auto res = make_json_response(notfound, 404);
send(client, res.c_str(), res.size(), 0);
close(client);
}
}
▶️ Compile and run
g++ api.cpp -o api -std=c++17
./api
👉 Visit:
http://localhost:7001/characters
To test sanitization:
http://localhost:7001/characters/1
🟦 Extra example in C++
💻 GUI Calculator with QT
What it does:
- Creates a small graphical calculator using Qt5.
- Takes two numbers as input.
- Provides four buttons: add, subtract, multiply, divide.
- Displays the result inside the window.
- Compiles using Qt5Widgets on Ubuntu.
To compile this file on Ubuntu:
# Install:
sudo apt install qtbase5-dev
📝 Crear archivo: touch qt-calc.cpp
▶️ Contenido del archivo: qt-calc.cpp
#include <QApplication>
#include <QWidget>
#include <QLineEdit>
#include <QPushButton>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QLabel>
int main(int argc, char *argv[]) {
QApplication app(argc, argv);
QWidget window;
window.setWindowTitle("Calculadora Qt");
// Inputs
QLineEdit *input1 = new QLineEdit();
QLineEdit *input2 = new QLineEdit();
QLabel *result = new QLabel("Resultado: ");
input1->setPlaceholderText("Número 1");
input2->setPlaceholderText("Número 2");
// Buttons
QPushButton *btnAdd = new QPushButton("+");
QPushButton *btnSub = new QPushButton("-");
QPushButton *btnMul = new QPushButton("*");
QPushButton *btnDiv = new QPushButton("/");
// Horizontal layout for buttons
QHBoxLayout *buttonsLayout = new QHBoxLayout();
buttonsLayout->addWidget(btnAdd);
buttonsLayout->addWidget(btnSub);
buttonsLayout->addWidget(btnMul);
buttonsLayout->addWidget(btnDiv);
// Main layout
QVBoxLayout *layout = new QVBoxLayout();
layout->addWidget(input1);
layout->addWidget(input2);
layout->addLayout(buttonsLayout);
layout->addWidget(result);
window.setLayout(layout);
// Helper function to calculate
auto calc = [&](char op) {
double a = input1->text().toDouble();
double b = input2->text().toDouble();
double r = 0;
switch (op) {
case '+': r = a + b; break;
case '-': r = a - b; break;
case '*': r = a * b; break;
case '/': r = (b != 0) ? a / b : 0; break;
}
result->setText("Resultado: " + QString::number(r));
};
// Connect buttons
QObject::connect(btnAdd, &QPushButton::clicked, [&]() { calc('+'); });
QObject::connect(btnSub, &QPushButton::clicked, [&]() { calc('-'); });
QObject::connect(btnMul, &QPushButton::clicked, [&]() { calc('*'); });
QObject::connect(btnDiv, &QPushButton::clicked, [&]() { calc('/'); });
window.show();
return app.exec();
}
▶️ Compilar y correr
g++ qt-calc.cpp -o app-qt-calc -fPIC $(pkg-config --cflags --libs Qt5Widgets)
./app-qt-calc

Top comments (0)