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

使用SDL2开发C++游戏时遭遇未定义引用错误求解决

SDL2函数未定义引用问题排查

我用C++结合SDL2开发游戏,编写了以下代码与Makefile,但编译运行时出现SDL相关函数的未定义引用错误。已将SDL2完整文件夹放入VS Code项目目录,代码中也完成了引用,但问题依旧。多次修改Makefile仍无法解决,相关内容如下:

main.cpp

#include <iostream>
#define SDL_MAIN_HANDLED
#include "SDL2/i686-w64-mingw32/include/SDL.h"

const int WIDTH = 800, HEIGHT = 600;

int main( int argc, char *argv[] )
{
    SDL_Init( SDL_INIT_EVERYTHING );

    SDL_Window *window = SDL_CreateWindow( "Hello SDL WORLD", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, WIDTH, HEIGHT, SDL_WINDOW_ALLOW_HIGHDPI );

    if ( NULL == window )
    {
        std::cout << "Could not create window: " << SDL_GetError( ) << std::endl;
        return 1;
    }

    SDL_Event windowEvent;

    while ( true )
    {
        if ( SDL_PollEvent( &windowEvent ) )
        {
            if ( SDL_QUIT == windowEvent.type )
            { break; }
        }
    }

    SDL_DestroyWindow( window );
    SDL_Quit( );

    return EXIT_SUCCESS;
}

Makefile

CC := g++
CFLAGS := -std=c++17 -I"C:/Users/ASUS/.vscode/gamedevelopment/SDL2/i686-w64-mingw32/include"
LFLAGS := -L"C:/Users/ASUS/.vscode/gamedevelopment/SDL2/i686-w64-mingw32/lib" -lSDL2 -lSDL2main

all: main

main: main.cpp
    $(CC) $(CFLAGS) $< $(LFLAGS) -o $@

.PHONY: clean
clean:
    rm -f main

错误信息

C:\Users\ASUS\AppData\Local\Temp\ccyIfXkF.o:main.cpp:(.text+0x1f): undefined reference to `SDL_Init'
C:\Users\ASUS\AppData\Local\Temp\ccyIfXkF.o:main.cpp:(.text+0x53): undefined reference to `SDL_CreateWindow'
C:\Users\ASUS\AppData\Local\Temp\ccyIfXkF.o:main.cpp:(.text+0x61): undefined reference to `SDL_GetError'
C:\Users\ASUS\AppData\Local\Temp\ccyIfXkF.o:main.cpp:(.text+0xa6): undefined reference to `SDL_PollEvent'
C:\Users\ASUS\AppData\Local\Temp\ccyIfXkF.o:main.cpp:(.text+0xc7): undefined reference to `SDL_DestroyWindow'
C:\Users\ASUS\AppData\Local\Temp\ccyIfXkF.o:main.cpp:(.text+0xcc): undefined reference to `SDL_Quit'
collect2.exe: error: ld returned 1 exit status

尝试过的其他Makefile配置

  • 直接命令行编译:
    g++ -std=c++17 main.cpp -I"src/include" -L"path/to/sdl2/library" -lSDL2 -lSDL2main -o main
    
  • 配置方案2:
    CXX = g++
    CXXFLAGS = -I src/include
    LDFLAGS = -L src/lib
    LDLIBS = -lmingw32 -lSDL2main -lSDL2
    
    ifeq ($(OS),Windows_NT)
        LDLIBS += -mwindows
    endif
    
    all: main
    
    main: main.cpp
        $(CXX) $(CXXFLAGS) $(LDFLAGS) -o main main.cpp $(LDLIBS)
    
  • 配置方案3:
    all:
        g++ -I src/include -L src/lib -o main main.cpp -lmingw32 -lSDL2main -lSDL2
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 17:44:49