經典 Win32 入門代碼報 error LNK2019: unresolved external symbol _WinProc@16。原因極其低級:**聲明與定義函數名拼寫不同**。
// 聲明
LRESULT CALLBACK WinProc(HWND, UINT, WPARAM, LPARAM);
// 定義
LRESULT CALLBACK WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) { ... }
聲明 WinProc,定義 WndProc,鏈接器找不到 WinProc 定義,報未解析外部符號。
// 統一為 WndProc (慣例命名)
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM); // 聲明
LRESULT CALLBACK WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) { ... } // 定義
/W4 警告等級,MSVC 會提示「函數聲明無定義」。#include
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
int WINAPI WinMain(HINSTANCE hInst, HINSTANCE, LPSTR, int nShow) {
WNDCLASS wc = {CS_HREDRAW|CS_VREDRAW, WndProc, 0,0, hInst, LoadIcon(0,IDI_APPLICATION), LoadCursor(0,IDC_ARROW), (HBRUSH)(COLOR_WINDOW+1), 0, L"MinWin"};
RegisterClass(&wc);
HWND hwnd = CreateWindow(L"MinWin", L"Hello", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, 400, 300, 0, 0, hInst, 0);
ShowWindow(hwnd, nShow);
MSG msg; while (GetMessage(&msg, 0, 0, 0)) { TranslateMessage(&msg); DispatchMessage(&msg); }
return msg.wParam;
}
LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp) {
switch (msg) {
case WM_DESTROY: PostQuitMessage(0); return 0;
case WM_PAINT: { PAINTSTRUCT ps; HDC hdc=BeginPaint(hwnd,&ps); TextOut(hdc,50,50,L"Hello Win32",11); EndPaint(hwnd,&ps); return 0; }
}
return DefWindowProc(hwnd, msg, wp, lp);
}
統一函數名,鏈接順利通過,Win32 之旅從這裡開始。