执行GDI+ C++截图存JPEG代码时出现`CreateStreamOnHGlobal@12'未定义引用错误的求助
CreateStreamOnHGlobal@12 Undefined Reference Error Hey there, let's break down why your screenshot code is failing to compile and how to fix it quickly!
The error you're seeing:
C:\Users\USER\AppData\Local\Temp\ccTLI53G.o:screenshot.cpp:(.text+0x158): undefined reference toCreateStreamOnHGlobal@12' collect2.exe: error: ld returned 1 exit status`
This is a linker error—your compiler knows what CreateStreamOnHGlobal is (thanks to including windows.h), but it can't find the actual implementation of the function in the libraries you're linking against.
What's the root cause?
CreateStreamOnHGlobal is a COM (Component Object Model) function that lives in the OLE32 library. Right now, your compile command only links against GDI+ (-lgdiplus)—you're missing the link to OLE32, which contains this function's definition.
The fix
Update your compile command to include the OLE32 library with the -lole32 flag:
g++ -mwindows screenshot.cpp -lgdiplus -lole32
This tells the linker exactly where to find the implementation of CreateStreamOnHGlobal, resolving the undefined reference error.
As a quick heads-up: COM-related functions often require linking against libraries like OLE32 or OLEAUT32. If you run into similar undefined reference issues with other COM functions down the line, checking those libraries is a good first step.
内容的提问来源于stack exchange,提问作者Kyle

