如何在不使用boost库的情况下在c ++中生成UUID?

时间:2014-06-23 11:58:05

标签: c++ uuid

我想为我的应用程序生成UUID,以区分我的应用程序的每个安装。我想在没有boost库支持的情况下使用C ++生成这个UUID。如何使用其他一些开源库生成UUID?

注意:我的平台是windows

6 个答案:

答案 0 :(得分:22)

如果您使用的是现代C ++,则可以。

#include <random>
#include <sstream>

namespace uuid {
    static std::random_device              rd;
    static std::mt19937                    gen(rd());
    static std::uniform_int_distribution<> dis(0, 15);
    static std::uniform_int_distribution<> dis2(8, 11);

    std::string generate_uuid_v4() {
        std::stringstream ss;
        int i;
        ss << std::hex;
        for (i = 0; i < 8; i++) {
            ss << dis(gen);
        }
        ss << "-";
        for (i = 0; i < 4; i++) {
            ss << dis(gen);
        }
        ss << "-4";
        for (i = 0; i < 3; i++) {
            ss << dis(gen);
        }
        ss << "-";
        ss << dis2(gen);
        for (i = 0; i < 3; i++) {
            ss << dis(gen);
        }
        ss << "-";
        for (i = 0; i < 12; i++) {
            ss << dis(gen);
        };
        return ss.str();
    }
}

答案 1 :(得分:11)

如评论中所述,您可以使用UuidCreate

#pragma comment(lib, "rpcrt4.lib")  // UuidCreate - Minimum supported OS Win 2000
#include <windows.h>
#include <iostream>

using namespace std;

int main()
{
    UUID uuid;
    UuidCreate(&uuid);
    char *str;
    UuidToStringA(&uuid, (RPC_CSTR*)&str);
    cout<<str<<endl;
    RpcStringFreeA((RPC_CSTR*)&str);
    return 0;
}

答案 2 :(得分:3)

ossp-uuid库可以生成UUID并具有C ++绑定。

使用起来似乎非常简单:

#include <uuid++.hh>
#include <iostream>

using namespace std;

int main() {
        uuid id;
        id.make(UUID_MAKE_V1);
        const char* myId = id.string();
        cout << myId << endl;
        delete myId;
}

请注意,它会分配并返回一个C样式的字符串,调用代码必须解除分配以避免泄漏。

另一种可能性是libuuid,它是util-linux软件包的一部分,可从ftp://ftp.kernel.org/pub/linux/utils/util-linux/获得。任何Linux机器都已安装它。它没有C ++ API,但仍然可以使用C API从C ++中调用。

答案 3 :(得分:1)

传统上,UUID只是机器的MAC地址与自西方采用公历以来100纳秒间隔的数量相结合。因此编写一个为您执行此操作的C ++ class并不困难。

答案 4 :(得分:1)

如果您只是想要随机的东西,我写了这个小函数:

string get_uuid() {
    static random_device dev;
    static mt19937 rng(dev());

    uniform_int_distribution<int> dist(0, 15);

    const char *v = "0123456789abcdef";
    const bool dash[] = { 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0 };

    string res;
    for (int i = 0; i < 16; i++) {
        if (dash[i]) res += "-";
        res += v[dist(rng)];
        res += v[dist(rng)];
    }
    return res;
}

答案 5 :(得分:0)

在 2021 年,我建议使用单头库 stduuid。它是跨平台的,不会引入任何不需要的依赖项。

从项目的 github 页面下载 uuid.h,然后一个最小的工作示例是:

#include <iostream>
#include <string>

#define UUID_SYSTEM_GENERATOR
#include "uuid.h"

int main (void) {
    std::string id = uuids::to_string (uuids::uuid_system_generator{}());
    std::cout << id << std::endl;
}

有关各种选项和生成器的更多详细信息和文档,请参阅项目的 github 页面。