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

SDL2编译报错:Window类构造与析构函数未定义引用

链接器错误:Window类构造与析构函数未定义引用

注:本人自4月30日开始学习SDL2,恳请谅解我的知识不足。

运行make命令时出现如下错误:

PS C:\Users\Admin\Desktop\SDLTuto> make
g++ -I src/include -L src/lib -o main main.cpp -lmingw32 -lSDL2main -lSDL2 
C:\Users\Admin\AppData\Local\Temp\ccymEbqx.o:main.cpp:(.text+0x48): undefined reference to `Window::Window(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, int, int)'
C:\Users\Admin\AppData\Local\Temp\ccymEbqx.o:main.cpp:(.text+0x81): undefined reference to `Window::~Window()'
collect2.exe: error: ld returned 1 exit status
make: *** [Makefile:2: all] Error 1

相关代码

window.h(类头文件)

#pragma once
#include <string>
#include <SDL2/SDL.h>

class Window {
public:
    Window(std::string title, int WIDTH, int HEIGHT);
    ~Window();
    inline const bool isClosed() {return closed;}
private:
bool init();

private:
    std::string _title;
    int _WIDTH = 800;
    int _HEIGHT = 600;

    bool closed = false;

    SDL_Window *window = nullptr;//nullptr = 0
};

Window类实现文件(假设为window.cpp)

#include "window.h"
#include <iostream>
//constructor
Window::Window(const std::string title, int WIDTH, int HEIGHT):
_title(title), _WIDTH(WIDTH), _HEIGHT(HEIGHT)
{
    if(!init()){
        closed = true;
    }
}

Window::~Window(){
    SDL_DestroyWindow(window);
    SDL_Quit();
}

bool Window::init(){
    if(SDL_Init(SDL_INIT_EVERYTHING)){
        std::cerr << "Failed to initialize SDL.\n";
        return 0;
    }
    window = SDL_CreateWindow(_title.c_str(), SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, _WIDTH, _HEIGHT, SDL_WINDOW_RESIZABLE);

    if (window == nullptr){
        std::cerr << "Failed to create window!\n";
        return 0;
    }

    return true;
}

main.cpp

#include "window.h"

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

    Window window("SDL TEST", 800, 600);

    while(!window.isClosed()){
        
    }
    return 0;
}

Makefile

all:
    g++ -I src/include -L src/lib -o main main.cpp -lmingw32 -lSDL2main -lSDL2 

问题原因与解决方法

问题根源

链接器报错是因为编译命令只包含了main.cpp,没有将Window类的实现文件(window.cpp)纳入编译流程。编译器仅能识别头文件中的类声明,找不到对应的函数实现代码,因此抛出"未定义引用"错误。

修复步骤

修改Makefile中的编译命令,将Window类的实现文件加入:

all:
    g++ -I src/include -L src/lib -o main main.cpp window.cpp -lmingw32 -lSDL2main -lSDL2 

若你的Window实现文件并非window.cpp,替换为实际文件名即可。执行修改后的make命令,链接器就能找到构造和析构函数的实现,错误即可解决。

额外补充:头文件中构造函数参数为std::string title,而实现中是const std::string title,虽不会引发链接错误,但建议保持声明与实现的参数一致(统一加上const更规范),避免后续潜在问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 03:43:24