0

So i'm trying to compile this simple piece of c++ code using gcc:

#include <windows.h>
#include <wingdi.h>

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
    HWND hwnd = GetDesktopWindow();
    HDC hdc = GetWindowDC(hwnd);
    RECT rekt;
    GetWindowRect(hwnd, &rekt);
        for (int i = 0; i < 50000; i++) {
            int x = rand() % 1920;
            int y = rand() % 1080;
            SetPixel(hdc, x, y, RGB(255, 255, 255));
        }
    ReleaseDC(hwnd, hdc);
}

and i'm using the following console command to (try to) build the executable:

.\g++.exe -lgdi32 -o output WindowsProject1.cpp

But i'm getting the following error:

WindowsProject1.cpp:(.text+0xcd): undefined reference to `SetPixel@16'
collect2.exe: error: ld returned 1 exit status

I'm guessing this is some linking issue? I'm pretty new to compiling c++, and it runs fine in Visual Studio, so i'm not quite sure what to do. As mentioned before, the command I'm using to build the executable does contain "-lgdi32" and this was an attempt of linking the library, but this still did not resolve the issue.

PS Jahn
  • 23
  • 5
  • Does this answer your question? [What is an undefined reference/unresolved external symbol error and how do I fix it?](https://stackoverflow.com/questions/12573816/what-is-an-undefined-reference-unresolved-external-symbol-error-and-how-do-i-fix) – Jesper Juhl Oct 26 '22 at 17:12
  • Order matters. I'm not sure if it does in this case, but typically you have to list the libraries needed AFTER the files that need those libraries so that the linker knows to look for the required items in the library. With `-lgdi32` at the beginning of the line, the linker may be scanning through gdi32 before it knows it needs to find `SetPixel`, so it doesn't bother building it into the program. Move it to the end: `g++.exe -o output test.cpp -lgdi32` – user4581301 Oct 26 '22 at 17:13
  • And now I'm sure. While writing above comment, I spun up a windows machine and tried it out. The order matters. Put the library at the end. – user4581301 Oct 26 '22 at 17:15

1 Answers1

1

Putting -lgdi32 at the end as suggested by @user4581301 fixed this issue.

James Risner
  • 5,451
  • 11
  • 25
  • 47
PS Jahn
  • 23
  • 5
  • Comments are not guaranteed to be permanent and can vanish in the future for any number of reasons. I recommend expanding the answer to explain why this works so that the answer still makes sense post-comment. – user4581301 Oct 26 '22 at 17:32