未定义的引用

问题描述 投票:0回答:3

链接器错误:

$ make
g++ -Wall -g main.cpp SDL_Helpers.cpp Game.cpp DrawableObject.cpp `sdl-config --cflags --libs` -lSDL_mixer
/tmp/ccdxzrej.o: In function `Game':
/home/brett/Desktop/SDL/Game.cpp:16: undefined reference to `Player::Player(Game*)'
/home/brett/Desktop/SDL/Game.cpp:16: undefined reference to `Player::Player(Game*)'
collect2: ld returned 1 exit status
make: *** [all] Error 1

main.cpp:

#include "Game.h"

int main()
{
    Game g;
    return 0;
}

游戏.h:

#ifndef BRETT_GAME_H
#define BRETT_GAME_H

#include <cmath>
#include "SDL.h"
#include "SDL_Helpers.h"
#include <vector>

class DrawableObject;

class Game
{
public:
    SDL_Surface * screen;
    std::vector<DrawableObject*> sprites;

    Game();
};

#endif

游戏.cpp:

#include "Game.h"
#include "DrawableObject.h"
#include "Player.h"

Game::Game()
{   
    if (SDL_Init(SDL_INIT_VIDEO) != 0)
        return;

    atexit(SDL_Quit);
    screen = SDL_SetVideoMode(640, 480, 0, SDL_DOUBLEBUF);

    if (screen == NULL)
        return;

    sprites.push_back(new Player(this));

    while (true)
    {
        SDL_Event * event = NULL;
        while(SDL_PollEvent(event) && event)
        {
            if(event->type == SDL_QUIT)
                return;
        }

        SDL_LockSurface(screen);

        for (uint32 i=0; i<sprites.size(); ++i)
        {
            sprites[i]->update(event);
        }

        SDL_FreeSurface(screen);
        SDL_Flip(screen);
    }
}

DrawableObject.h:

#ifndef DRAWABLE_OBJECT_H
#define DRAWABLE_OBJECT_H

#include "SDL.h"
#include "SDL_Helpers.h"

class Game;

class DrawableObject
{
public:
    Game * const game;

    DrawableObject(Game * const game_);

    virtual void update(SDL_Event *event) = 0;

};

#endif

DrawableObject.cpp:

#include "DrawableObject.h"
#include "Game.h"

DrawableObject::DrawableObject(Game * const game_)
    :   game(game_)
{

}

Player.h:

#ifndef PLAYER_H
#define PLAYER_H

#include <cmath>
#include "DrawableObject.h"

class Player : public DrawableObject
{
public:
    Player(Game * const game);

    void update(SDL_Event *event);
};

#endif

播放器.cpp:

#include "Player.h"
#include "Game.h"

Player::Player(Game * const game)
    : DrawableObject(game)
{

}

void Player::update(SDL_Event *event)
{
    draw_circle(game->screen, 100, 100, 50, 0xff000000);
}
c++ linker undefined-reference
3个回答
7
投票

您的编译行中缺少 Player.cpp。您遇到链接错误。


0
投票

不是循环依赖问题(至少不是您当前提出的问题)。你忘了编译

Player.cpp


0
投票

供遇到此问题的其他人参考:如果您在 makefile 中的 G++ 命令中遗漏了输出文件,您也会收到相同的错误。

© www.soinside.com 2019 - 2024. All rights reserved.