Creating a Globally Unique Identifier

by Richard Russell, April 2007

A Globally Unique Identifier, or GUID for short, is a 128-bit (16 byte) number which, as its name suggests, is intended to be unique in the world - or possibly in the universe! GUIDs are often represented in a textual form as follows:

{A8A8D3E5-713D-4C00-897E-F3B225E3A3AF}

GUIDs are used for a number of purposes in Windows, most notably to identify a COM interface (IID) or class (CLSID); in those cases you must discover the correct value to use from Microsoft's documentation.

GUIDs are also useful whenever you need to identify something uniquely. For example in the article Detecting a second instance of a program it is suggested that a GUID be used as the UniqueLockName. In such cases it is up to you to create a GUID for the purpose.

There is no guarantee that a GUID is genuinely unique, but statistically the likelihood of any two being the same is small. Whilst you could simply make up your own 128-bit number 'at random' (whatever that means) it is far better to use one of the means provided specially for the purpose. One is the following website, which will create a new GUID on request: http://www.famkruithof.net/uuid/uuidgen.

An alternative method is to use your own program. The code below will generate a new GUID whenever you need one:

        SYS "LoadLibrary", "OLE32.DLL" TO ole32%
        SYS "GetProcAddress", ole32%, "CoCreateGuid" TO CoCreateGuid%
        SYS "GetProcAddress", ole32%, "StringFromGUID2" TO StringFromGUID2%
 
        DIM guid{a%, b%, c%, d%}, guidw% 79, guida% 39
        SYS CoCreateGuid%, guid{}
        SYS StringFromGUID2%, guid{}, guidw%, 40
        SYS "WideCharToMultiByte", 0, 0, guidw%, -1, guida%, 40, 0, 0
        PRINT $$guida%

The GUID is available as a 128-bit number in the structure guid{}, as a Unicode (16-bit) string at guidw% and as a NUL-terminated ANSI (8-bit) string at guida%.