I have this code:
// Include guiddef.h
#include <guiddef.h>
// Define GUID
DEFINE_GUID(MyGuid,
0x12345678, 0x1234, 0x5678, 0x12, 0x34, 0x56, 0x78, 0x9A, 0xBC, 0xDE, 0xF0);
int main() {
// Initialize variable with defined GUID
GUID guid = MyGuid;
// Can also directly use MyGuid
return 0;
}
and when I compile it using VS 2022, 17.6.5, I am getting this linker error:
Error LNK2001 unresolved external symbol MyGuid testApplication 1
Why I am getting this error?
DEFINE_GUIDuses kind of a semi-ugly hack that works in C, but not in C++.When you use
DEFINE_GUID, it tacks anexternon the beginning of the code it generates. In C, this is fairy harmless--you end up with what's called a "tentative definition". A tentative definition is kind of a halfway point between a declaration and a definition. On one hand, you can have multiple tentative definitions of the same name, and as long as they don't conflict (like trying to give it different types) that's all right. But it will also act as a definition if there's no non-tentative definition visible.The closest equivalent of this in C++ would be an
inlinevariable definition (which can also have multiple occurrences, as long as they don't conflict, and they all resolve to a single object in the end). But, as it stands right now, the macro expands to something that includesexternon the beginning, and in C++ that's strictly a declaration, not a definition, so when/if you try to use this in C++, you don't have a definition anywhere, and linking fails.Reference
https://learn.microsoft.com/en-us/windows-hardware/drivers/kernel/defining-and-exporting-new-guids