Code guide

Generate UUIDs in C++

Generate UUIDs in C++ using Boost.UUID, with random v4 generation and string conversion examples.

C++ has no standard UUID type, so most projects use Boost.UUID, a mature header library that generates and formats UUIDs.

Key takeaways

  • Boost.UUID is the common choice for C++ UUIDs.
  • random_generator produces a version 4 UUID.
  • to_string converts a UUID to canonical text.

For implementation context, continue with UUID v4, UUID Versions, and Go. These pages cover the closest generator, comparison, validation or storage decisions without repeating this guide.

Generate a random UUID with Boost

Create a random_generator once and call it to produce version 4 values, then convert to a string for output or storage.

#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 id = gen();          // version 4
    std::cout << boost::uuids::to_string(id) << "\n";
}

Parse a UUID string

Use the string generator to parse canonical text into a uuid, which throws on clearly invalid input.

#include <boost/uuid/string_generator.hpp>

boost::uuids::string_generator parse;
boost::uuids::uuid id = parse("018f2f7a-07b2-7d6e-9c37-43e1577b8b44");

FAQ

Generate UUIDs in C++ questions

Does C++ have a standard UUID type?

No. The C++ standard library has no UUID type, so Boost.UUID or a platform library is commonly used.

Is Boost.UUID random secure?

random_generator uses a strong random source by default, which is suitable for identifiers.

How do I convert a Boost UUID to a string?

Call boost::uuids::to_string(id) to get the canonical lowercase form.

Generate UUID in C++ - Boost.UUID Examples