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

C++链接错误:SpriteAnimation类成员函数未定义引用求助

解决C++链接错误:undefined reference to SpriteAnimation相关函数

你遇到的链接错误如下:

/src/main.cpp:10: undefined reference to `SpriteAnimation::SpriteAnimation(char const*, int, int, int, int, float)'
/src/main.cpp:17: undefined reference to `SpriteAnimation::Update(float)'
/src/main.cpp:23: undefined reference to `SpriteAnimation::Draw(Vector2, float, Color)'
/src/main.cpp:30: undefined reference to `SpriteAnimation::~SpriteAnimation()'
/src/main.cpp:30: undefined reference to `SpriteAnimation::~SpriteAnimation()'
collect2.exe: error: ld returned 1 exit status

问题根源

你的SpriteAnimation.cpp犯了典型的C++类实现错误:在cpp文件中重新定义了整个SpriteAnimation类,而非针对头文件里声明的类成员做实现。这会让编译器把cpp里的类当成一个全新的、和头文件无关的类,链接器找不到main.cpp调用的头文件类的函数实现,从而抛出"undefined reference"错误。

修正后的SpriteAnimation.cpp

正确写法是先包含头文件,再用类名::函数名的方式实现成员函数:

#include "SpriteAnimation.h"
#include "raylib.h"
#include <vector>

SpriteAnimation::SpriteAnimation(const char* filename, int frameWidth, int frameHeight, int framesPerRow, int framesPerColumn, float fps) {
    spriteSheet = LoadTexture(filename);
    currentFrame = 0;
    frameTime = 1.0f / fps;
    timer = 0.0f;

    // 计算并存储所有帧的矩形区域
    for (int y = 0; y < framesPerColumn; y++) {
        for (int x = 0; x < framesPerRow; x++) {
            Rectangle frame = {
                static_cast<float>(x * frameWidth),
                static_cast<float>(y * frameHeight),
                static_cast<float>(frameWidth),
                static_cast<float>(frameHeight)
            };
            frames.push_back(frame);
        }
    }
}

SpriteAnimation::~SpriteAnimation() {
    UnloadTexture(spriteSheet);
}

void SpriteAnimation::Update(float deltaTime) {
    timer += deltaTime;
    if (timer >= frameTime) {
        currentFrame = (currentFrame + 1) % frames.size();
        timer = 0.0f;
    }
}

void SpriteAnimation::Draw(Vector2 position, float scale, Color tint) {
    DrawTexturePro(
        spriteSheet,
        frames[currentFrame],
        {position.x, position.y, frames[currentFrame].width * scale, frames[currentFrame].height * scale},
        {0, 0},
        0.0f,
        tint
    );
}

编译注意事项

编译时要确保把所有相关cpp文件都纳入编译流程,比如使用g++的Windows平台命令:

g++ main.cpp SpriteAnimation.cpp -o animation_example -lraylib -lopengl32 -lgdi32 -lwinmm

其他平台请调整对应的raylib依赖库参数。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 22:40:10