Last Modification: May 25, 2006

I get linker error LNK2001 for symbol IID_xxx, even though I included the correct headers and added the lib files as linker input.

This is likely caused by the fact that those symbols are only declared, but never defined. You can solve this by including initguid.h before the header file that contains the IID_xxx symbol.

Explanation:

GUIDs are structure data types. If you look at the DEFINE_GUID macro, it looks like this:


#ifdef INITGUID
#define DEFINE_GUID(name, l, w1, w2, b1, b2, b3, b4, b5, b6, b7, b8) \
        EXTERN_C const GUID DECLSPEC_SELECTANY name \
                = { l, w1, w2, { b1, b2,  b3,  b4,  b5,  b6,  b7,  b8 } }
#else
#define DEFINE_GUID(name, l, w1, w2, b1, b2, b3, b4, b5, b6, b7, b8) \
    EXTERN_C const GUID FAR name
#endif // INITGUID

If INITGUID is defined, the DEFINE_GUID macro is expanded into a declaration of a variable with the given name, and a value that corresponds to the value of the GUID.

If INITGUID is not defined, the DEFINE_GUID macro is simply expanded into a declaration for an external variable with the given name.

As a result, if it is always expanded into a declaration (because INITGUID is never defined), the linker will never be able to locate the GUID variable itself. This will result in linker error LNK2001.

This issue is also explained on the Microsoft support site: http://support.microsoft.com/default.aspx?scid=kb%3Ben-us%3B130869

The following code sample demonstrates the problem and the solution:


#include <unknwn.h>
//#include <initguid.h> //uncomment to solve LNK2001

DEFINE_GUID(IID_CLSID_LNK2001, 
0xc190f2d7, 0xcf75, 0x474c, 0x81, 0x78, 0x29, 0x2b, 0xdc, 0x83, 0x14, 0x81);

int _tmain(int argc, _TCHAR* argv[])
{
  IUnknown *iUnknwn = NULL;
  HRESULT hResult;
  hResult = CoCreateInstance(
              IID_CLSID_LNK2001,
              NULL,
              0,
              IID_IUnknown,
              (LPVOID *)&iUnknwn);
	return 0;
}

It is also important that the GUID is instantiated only once per application or dll. Otherwise you will get a linker error because the same IID_xxx symbol is found in multiple places.

Acknowledgements

This FAQ was contributed by Bruno van Dooren.