Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Platform-independent GUID generation in C++?

What is the best way to programmatically generate a GUID or UUID in C++ without relying on a platform-specific tool? I am trying to make unique identifiers for objects in a simulation, but can't rely on Microsoft's implementation as the project is cross-platform.

Notes:

  • Since this is for a simulator, I don't really need cryptographic randomness.
  • It would be best if this is a 32 bit number.
like image 357
Moses Schwartz Avatar asked Feb 12 '09 21:02

Moses Schwartz


People also ask

What is GUID generator?

A GUID (globally unique identifier) is a 128-bit text string that represents an identification (ID). Organizations generate GUIDs when a unique reference number is needed to identify information on a computer or network. A GUID can be used to ID hardware, software, accounts, documents and other items.

How does GUID generate?

Basically, a a GUID is generated using a combination of: The MAC address of the machine used to generate the GUID (so GUIDs generated on different machines are unique unless MAC addresses are re-used) Timestamp (so GUIDs generated at different times on the same machine are unique)

What is the difference between UUID and GUID?

UUID is a term that stands for Universal Unique Identifier. Similarly, GUID stands for Globally Unique Identifier. So basically, two terms for the same thing. They can be used, just like a product number, as a unique reference for an academic standard or content title.

What is GUID algorithm?

The GUID generation algorithm relies on the fact that it has all 16 bytes to use to establish uniqueness, and if you throw away half of it, you lose the uniqueness. There are multiple GUID generation algorithms, but I'll pick one of them for concreteness, specifically the version described in this Internet draft.


2 Answers

If you can afford to use Boost, then there is a UUID library that should do the trick. It's very straightforward to use - check the documentation and this answer.

like image 76
Anonymous Avatar answered Sep 19 '22 11:09

Anonymous


on linux: man uuid

on win: check out for UUID structure and UuidCreate function in msdn

[edit] the function would appear like this

extern "C" { #ifdef WIN32 #include <Rpc.h> #else #include <uuid/uuid.h> #endif }  std::string newUUID() { #ifdef WIN32     UUID uuid;     UuidCreate ( &uuid );      unsigned char * str;     UuidToStringA ( &uuid, &str );      std::string s( ( char* ) str );      RpcStringFreeA ( &str ); #else     uuid_t uuid;     uuid_generate_random ( uuid );     char s[37];     uuid_unparse ( uuid, s ); #endif     return s; } 
like image 29
ubik Avatar answered Sep 20 '22 11:09

ubik