You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用GCC编译Windows API代码时SetPixel@16未定义引用问题

解决GCC编译Windows API时SetPixel@16未定义引用的问题

核心问题原因

这个错误是因为链接阶段缺少了包含SetPixel函数的系统库。SetPixel属于Windows User32库,GCC编译Windows程序时,默认不会自动链接该库,必须手动指定链接参数。

解决步骤

1. 添加链接参数

在VSCode的编译配置(tasks.json)中,给GCC添加-luser32链接选项。直接在终端编译的话,命令应为:

g++ main.cpp -o pixel.exe -luser32

若使用tasks.json配置编译任务,示例如下:

{
    "version": "2.0.0",
    "tasks": [
        {
            "label": "compile",
            "type": "shell",
            "command": "g++",
            "args": [
                "main.cpp",
                "-o",
                "pixel.exe",
                "-luser32"
            ],
            "group": {
                "kind": "build",
                "isDefault": true
            },
            "problemMatcher": ["$gcc"]
        }
    ]
}

2. 修复代码逻辑问题

原代码中rand()的种子初始化位置错误:srand(time(NULL))放在消息循环之后,会导致随机数种子从未被初始化,每次运行生成的像素位置完全一致。需要将其移到WinMain函数开头:

int WINAPI 
WinMain (HINSTANCE hInstance, HINSTANCE hPrevInst, LPTSTR lpCmdLine, int nShowCmd) {
    srand(time(NULL)); // 移至此处初始化随机数种子
    MSG  msg;
    // 其余代码保持不变
}

修改后的完整代码

#include <windows.h>
#include <time.h>

LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
void DrawPixels(HWND hwnd);

int WINAPI 
WinMain (HINSTANCE hInstance, HINSTANCE hPrevInst, LPTSTR lpCmdLine, int nShowCmd) {
    srand(time(NULL));
    MSG  msg;
    WNDCLASSW wc = {0};

    wc.style = CS_HREDRAW | CS_VREDRAW;
    wc.lpszClassName = L"Pixels";
    wc.hInstance     = hInstance;
    wc.hbrBackground = GetSysColorBrush(COLOR_3DFACE);
    wc.lpfnWndProc   = WndProc;
    wc.hCursor       = LoadCursor(0, IDC_ARROW);

    RegisterClassW(&wc);
    CreateWindowW(wc.lpszClassName, L"Pixels",
                WS_OVERLAPPEDWINDOW | WS_VISIBLE,
                100, 100, 300, 250, NULL, NULL, hInstance, NULL);

    while (GetMessage(&msg, NULL, 0, 0)) {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }

    return (int) msg.wParam;
}

LRESULT CALLBACK WndProc(HWND hwnd, UINT msg,
    WPARAM wParam, LPARAM lParam) {

    switch(msg) {
        case WM_PAINT:
            DrawPixels(hwnd);
            break;
        case WM_DESTROY:
            PostQuitMessage(0);
            return 0;
    }
    return DefWindowProcW(hwnd, msg, wParam, lParam);
}

void DrawPixels(HWND hwnd) {
    PAINTSTRUCT ps;
    RECT r;
    GetClientRect(hwnd, &r);

    if (r.bottom == 0) {
        return;
    }

    HDC hdc = BeginPaint(hwnd, &ps);
    for (int i=0; i<1000; i++) {
        int x = rand() % r.right;
        int y = rand() % r.bottom;
        SetPixel(hdc, x, y, RGB(255, 0, 0));
    }
    EndPaint(hwnd, &ps);
}

内容的提问来源于stack exchange,提问作者Mason Cooreman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 00:10:45