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

命令行编译C程序遭遇LNK2019未解析外部符号错误求助

解决命令行编译Windows控制台GDI代码的LNK2019错误

问题场景

以下代码用于在控制台窗口绘制十字线,在Visual Studio IDE中可正常编译运行,但使用cl test.c命令行编译时,出现未解析外部符号的链接错误:

示例代码

#include <stdio.h>
#include <windows.h>

int main()
{
    HWND myconsole = GetConsoleWindow();
    HDC mydc = GetDC(myconsole);
    RECT rect;
    GetClientRect(myconsole, &rect);
    for(int i = 0; i < rect.bottom - rect.top; ++i)
        SetPixel(mydc, (rect.right - rect.left) / 2, i, RGB(255, 0, 0));
    for(int i = 0; i < rect.right - rect.left; ++i)
        SetPixel(mydc, i, (rect.bottom - rect.top) / 2, RGB(255, 0, 0));
}

编译错误信息

error LNK2019: unresolved external symbol __imp__SetPixel@16 referenced in function _main
error LNK2019: unresolved external symbol __imp__GetDC@4 referenced in function _main
error LNK2019: unresolved external symbol __imp__GetClientRect@8 referenced in function _main

解决方案

出现该错误的核心原因是:SetPixel、GetDC、GetClientRect属于Windows系统的user32.lib和gdi32.lib库,Visual Studio IDE会自动链接这些常用系统库,但命令行下的cl编译器不会默认完成这个操作,需要手动指定链接依赖。

有两种可行的解决方式:

方式1:命令行编译时显式指定链接库

在编译命令末尾添加需要链接的库文件:

cl test.c user32.lib gdi32.lib

方式2:在代码中添加编译指令

通过#pragma comment指令,在代码中告诉编译器自动链接所需库,修改后的代码如下:

#include <stdio.h>
#include <windows.h>
#pragma comment(lib, "user32.lib")
#pragma comment(lib, "gdi32.lib")

int main()
{
    HWND myconsole = GetConsoleWindow();
    HDC mydc = GetDC(myconsole);
    RECT rect;
    GetClientRect(myconsole, &rect);
    for(int i = 0; i < rect.bottom - rect.top; ++i)
        SetPixel(mydc, (rect.right - rect.left) / 2, i, RGB(255, 0, 0));
    for(int i = 0; i < rect.right - rect.left; ++i)
        SetPixel(mydc, i, (rect.bottom - rect.top) / 2, RGB(255, 0, 0));
}

两种方式都能解决链接错误,可根据使用习惯任选其一。

内容的提问来源于stack exchange,提问作者Derek Johnson

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 01:15:08