C++ 生成GUID的幾種方法git
一。github
使用CoCreateGuid函數
CoCreateGuid是Windows系統自己提供的API函數,位於objbase.h
頭文件中,dom
1 #include <objbase.h> 2 #include <stdio.h> 3 4 #define GUID_LEN 64 5 6 int main(int argc, char* argv[]) 7 { 8 char buffer[GUID_LEN] = { 0 }; 9 GUID guid; 10 11 if ( CoCreateGuid(&guid) ) 12 { 13 fprintf(stderr, "create guid error\n"); 14 return -1; 15 } 16 _snprintf(buffer, sizeof(buffer), 17 "%08X-%04X-%04x-%02X%02X-%02X%02X%02X%02X%02X%02X", 18 guid.Data1, guid.Data2, guid.Data3, 19 guid.Data4[0], guid.Data4[1], guid.Data4[2], 20 guid.Data4[3], guid.Data4[4], guid.Data4[5], 21 guid.Data4[6], guid.Data4[7]); 22 printf("guid: %s\n", buffer); 23 24 return 0; 25 26 }
這種基於Win32API生成GUID的方法的優勢在於不須要依賴其餘庫,缺點在於沒法跨平臺,只能在Windows平臺的使用。ide
二 函數
使用Boost庫
使用Boost庫來生成GUID相對就比較簡單了,代碼以下:ui
#include <boost/uuid/uuid.hpp> #include <boost/uuid/uuid_generators.hpp> #include <boost/uuid/uuid_io.hpp> boost::uuids::uuid uid = boost::uuids::random_generator()(); const string uid_str = boost::uuids::to_string(uid); cout << uid_str << endl;
三。this
UUID Generation in C++11
1 #include <sstream> 2 #include <random> 3 #include <string> 4 5 unsigned int random_char() { 6 std::random_device rd; 7 std::mt19937 gen(rd()); 8 std::uniform_int_distribution<> dis(0, 255); 9 return dis(gen); 10 } 11 12 std::string generate_hex(const unsigned int len) { 13 std::stringstream ss; 14 for (auto i = 0; i < len; i++) { 15 const auto rc = random_char(); 16 std::stringstream hexstream; 17 hexstream << std::hex << rc; 18 auto hex = hexstream.str(); 19 ss << (hex.length() < 2 ? '0' + hex : hex); 20 } 21 return ss.str(); 22 }
https://lowrey.me/guid-generation-in-c-11/spa
The C++ standard libary has come a long way in the last ten years. It contains a lot of useful functions that make stuff easy that used to be a chore in C++ compared to other languages. However, there is still a gap between what the STL provides compared to other modern languages.code
One such case is UUID/GUID creation. In languages like Python and Java, to make a GUID, all you need to do is import a module and you are good to go. In C++, this will still be relegated to an external framework like the Windows API or QT. There are even some smaller cross platform libraries specifically targeting this functionality. In most cases, this is still the best place to go. These methods are battle-tested: they'll be fast and robust.orm
If you want something more portable that doesn't rely on any external linking, you'll have to write it yourself. Luckily, the UUID format isn't particularly complex. If you can generate random hex characters, you can make a GUID easily.
The STL in C++11 now includes std::random
which makes this a lot easier. Before it, you would still probably need to go to an external library to get random values. In combination with std::hex, almost all of the hard parts of this problem can be solved with stuff in the standard library.