首页 > 解决方案 > 错误: - 未定义引用 `_imp__GetStockObject@4' 和未定义引用 `_imp__SetBkMode@8'

问题描述

我在 c++ 中的 windows10 中的 Visual Studio 代码中编写了一个代码,以获得简单的窗口,但无法构建和运行所有用于调试的文件,如 task.json、launch.json 和 cpp-properties.json,请告诉我如何制作Visual Studio 代码中的 windows 项目。

错误是

> Executing task: g++ -g -lgdi32 main.cpp <

C:\Users\abhi\AppData\Local\Temp\cc0d0bc2.o: In function `WinMain@16':
C:\Users\abhi\Desktop\abs/main.cpp:38: undefined reference to `_imp__GetStockObject@4'
C:\Users\abhi\AppData\Local\Temp\cc0d0bc2.o: In function `Z10WindowProcP6HWND__jjl@16':
C:\Users\abhi\Desktop\abs/main.cpp:91: undefined reference to `_imp__SetBkMode@8'
collect2.exe: error: ld returned 1 exit status
The terminal process terminated with exit code: 1

主文件

#include <windows.h>
#include <tchar.h>

LRESULT CALLBACK WindowProc(HWND hWnd, UINT message,
  WPARAM wParam, LPARAM lParam);

// Listing OFWIN_1
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
  LPSTR lpCmdLine, int nCmdShow)
{
  WNDCLASSEX WindowClass;                        // Structure to hold our window's attributes

  static LPCTSTR szAppName { _T("OFWin") };      // Define window class name
  HWND hWnd;                                     // Window handle
  MSG msg;                                       // Windows message structure

  WindowClass.cbSize = sizeof(WNDCLASSEX);       // Set structure size

  // Redraw the window if the size changes
  WindowClass.style = CS_HREDRAW | CS_VREDRAW;

  // Define the message handling function
  WindowClass.lpfnWndProc = WindowProc;

  WindowClass.cbClsExtra = 0;                    // No extra bytes after the window class
  WindowClass.cbWndExtra = 0;                    // structure or the window instance

  WindowClass.hInstance = hInstance;             // Application instance handle

  // Set default application icon
  WindowClass.hIcon = LoadIcon(nullptr, IDI_APPLICATION);

  // Set window cursor to be the standard arrow
  WindowClass.hCursor = LoadCursor(nullptr, IDC_ARROW);

  // Set gray brush for background color
  WindowClass.hbrBackground = static_cast<HBRUSH>(GetStockObject(GRAY_BRUSH));

  WindowClass.lpszMenuName = nullptr;            // No menu
  WindowClass.lpszClassName = szAppName;         // Set class name
  WindowClass.hIconSm = nullptr;                 // Default small icon

  // Now register our window class
  RegisterClassEx(&WindowClass);

  // Now we can create the window
  hWnd = CreateWindow(
    szAppName,                                   // the window class name
    _T("A Basic Window the Hard Way"),           // The window title
    WS_OVERLAPPEDWINDOW,                         // Window style as overlapped
    CW_USEDEFAULT,                               // Default screen position of upper left
    CW_USEDEFAULT,                               // corner of our window as x,y.
    CW_USEDEFAULT,                               // Default window size width ...
    CW_USEDEFAULT,                               // ... and height
    nullptr,                                     // No parent window
    nullptr,                                     // No menu
    hInstance,                                   // Program Instance handle
    nullptr                                      // No window creation data
    );

  ShowWindow(hWnd, nCmdShow);                    // Display the window
  UpdateWindow(hWnd);                            // Redraw window client area 

  // The message loop
  while (GetMessage(&msg, nullptr, 0, 0) == TRUE) // Get any messages
  {
    TranslateMessage(&msg);                      // Translate the message
    DispatchMessage(&msg);                       // Dispatch the message
  }

  return static_cast<int>(msg.wParam);           // End, so return to Windows
}

// Listing OFWIN_2
LRESULT CALLBACK WindowProc(HWND hWnd, UINT message,
  WPARAM wParam, LPARAM lParam)
{

  switch (message)                               // Process selected messages
  {
  case WM_PAINT:                                 // Message is to redraw the window
    HDC hDC;
    PAINTSTRUCT PaintSt;                         // Structure defining area to be drawn
    hDC = BeginPaint(hWnd, &PaintSt) ;           // Prepare to draw the window

    // Get upper left and lower right of client area
    RECT aRect;                                  // A working rectangle
    GetClientRect(hWnd, &aRect);

    SetBkMode(hDC, TRANSPARENT);                 // Set text background mode

    // Now draw the text in the window client area
    DrawText(
      hDC,                                       // Device context handle
      _T("But, soft! What light through yonder window breaks?"),
      -1,                                        // Indicate null terminated string
      &aRect,                                    // Rectangle in which text is to be drawn
      DT_SINGLELINE |                            // Text format - single line
      DT_CENTER |                                //             - centered in the line
      DT_VCENTER);                               //             - line centered in aRect

    EndPaint(hWnd, &PaintSt);                    // Terminate window redraw operation
    return 0;

  case WM_DESTROY:                               // Window is being destroyed
    PostQuitMessage(0);
    return 0;
  }
  return DefWindowProc(hWnd, message, wParam, lParam);
}

任务.json

{
    // See https://go.microsoft.com/fwlink/?LinkId=733558
    // for the documentation about the tasks.json format
    "version": "2.0.0",
    "tasks": [
        {
            "label": "echo",
            "type": "shell",
            "command": "g++ -g main.cpp",
            "group": {
                "kind": "build",
                "isDefault": true
            }
        }
    ]
}

启动.json

{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "name": "(gdb) Launch",
            "type": "cppdbg",
            "request": "launch",
            "program": "${workspaceFolder}/a.exe",
            "args": [],
            "stopAtEntry": false,
            "cwd": "${workspaceFolder}",
            "environment": [],
            "externalConsole": true,
            "MIMode": "gdb",
            "miDebuggerPath": "C:\\Program Files (x86)\\mingw-w64\\i686-8.1.0-posix-dwarf-rt_v6-rev0\\mingw32\\bin\\gdb.exe",
            "preLaunchTask": "echo",
            "setupCommands": [
                {
                    "description": "Enable pretty-printing for gdb",
                    "text": "-enable-pretty-printing",
                    "ignoreFailures": true
                }
            ]
        }
    ]
}

cpp properties.json

{
    "configurations": [
        {
            "name": "Win32",
            "includePath": [
                "C:\\Program Files (x86)\\mingw-w64\\i686-8.1.0-posix-dwarf-rt_v6-rev0\\mingw32\\lib\\gcc\\i686-w64-mingw32\\8.1.0\\include\\c++"
            ],
            "defines": [
                "_DEBUG",
                "UNICODE",
                "_UNICODE"
            ],
            "windowsSdkVersion": "8.1",
            "cStandard": "c11",
            "cppStandard": "c++17",
            "intelliSenseMode": "clang-x64",
            "compilerPath": "C:\\Program Files (x86)\\mingw-w64\\i686-8.1.0-posix-dwarf-rt_v6-rev0\\mingw32\\bin\\gcc.exe"
        }
    ],
    "version": 4
}

标签: visual-studio-codec++17

解决方案


您正在使用Visual Studio Code,但这个问题实际上VSCode 无关,因为可以通过在命令提示符(Windowscmd.exe或 Cygwin bash)下运行您的第一个命令来重现该问题:

  > g++ -g -lgdi32 main.cpp
  (errors as above)

由于您尝试使用 MinGW gcc 构建 Windows 程序,因此您需要传递-mwindows选项:

  > g++ -g -mwindows main.cpp
  (works)
  > ./a.exe
  (runs)

添加-mwindows到您的tasks.json命令中,它也应该在 VSCode 中工作。


推荐阅读