Skip to main content
C++

How to Generate UUID in C++

Cross-platform UUID generation guide

C++ has no built-in UUID type, even as of C++23, so you'll need the Boost.UUID library to produce a properly formatted 128-bit identifier without writing the bit-fiddling code yourself. Add three headers, call boost::uuids::random_generator(), and you get an RFC 4122-compliant UUID that prints straight to std::cout. Below you'll find copy-paste ready code for generating a UUID in C++, parsing a string back into a boost::uuids::uuid, and the platform-native alternatives worth knowing about. For browser-based UUID generation without dependencies, the javascript uuid guide uses the Web Crypto API directly.

Generate UUID in C++

boost::uuids::uuid id = gen();
550e8400-e29b-41d4-a716-446655440000

How to Generate a UUID in C++

The most portable way to generate a UUID in C++ is Boost.UUID's random_generator, which produces a random, RFC 4122-compliant UUID v4 without depending on any OS-specific API. The r uuid reference explains how to use uuid::UUIDgenerate() for random v4 identifiers in R.

main.cpp
#include <boost/uuid/uuid.hpp>
#include <boost/uuid/uuid_generators.hpp>
#include <boost/uuid/uuid_io.hpp>
#include <iostream>

int main() {
    boost::uuids::random_generator gen;
    boost::uuids::uuid my_uuid = gen();

    std::cout << my_uuid << std::endl;
    // Output: 550e8400-e29b-41d4-a716-446655440000

    return 0;
}

Explanation

Convert a String to a UUID in C++

When a UUID arrives as a string — from a config file, command-line argument, or network payload — Boost's string_generator parses it back into a proper boost::uuids::uuid object. For uuid in rust in async web services, the page includes complete Actix-web and Axum handler examples.

main.cpp
#include <boost/uuid/uuid.hpp>
#include <boost/uuid/uuid_io.hpp>
#include <boost/uuid/string_generator.hpp>
#include <iostream>

int main() {
    boost::uuids::string_generator gen;
    boost::uuids::uuid u = gen("550e8400-e29b-41d4-a716-446655440000");

    std::cout << u << std::endl;

    return 0;
}

Explanation

Other Options for Generating UUIDs in C++

Boost.UUID covers most projects, but if you'd rather skip the dependency, both major platforms expose a native UUID/GUID generator you can call directly instead.

platform-native.cpp
#ifdef _WIN32
#include <objbase.h>
#pragma comment(lib, "ole32.lib")

GUID my_guid;
CoCreateGuid(&my_guid);
#endif

#ifdef __linux__
#include <uuid/uuid.h>

uuid_t my_uuid;
char uuid_str[37];
uuid_generate(my_uuid);
uuid_unparse(my_uuid, uuid_str);
#endif

Explanation

Comments & Feedback

Share your experience or ask questions about this tool

Copied!