3
\$\begingroup\$

So I've been following an SFML tutorial but unfortunately, it doesn't seem to be working. The tutorial shows a RenderWindow as a global variable and then accesses it like this:

LevelState.h:

struct LevelStateAssets
{
sf::Texture img_background;
sf::Texture img_player;
sf::Texture img_enemy;
};

extern LevelStateAssets ls_Assets;

class LevelState : public StateBase
{
public:
    LevelState();
    void Input(sf::Event event);
    void Update(void);
    void Render(void);

private:
    sf::Sprite spr_background;
};

LevelState.cpp:

LevelStateAssets ls_Assets;

LevelState::LevelState()
{
ls_Assets.img_background.loadFromFile("res/images/background.png");
ls_Assets.img_player.loadFromFile("res/images/player.png");
ls_Assets.img_enemy.loadFromFile("res/images/enemy.png");

spr_background.setTexture(ls_Assets.img_background);
spr_background.setPosition(0, 0);
}
/* More unnecessary code in the middle */

void LevelState::Render(void)
{
window.draw(spr_background);
}

But when I do this, I get an error that says: "Unhandled exception at 0x774F3632 (ntdll.dll) in SFMLTutorial.exe: 0xC0000005: Access violation writing location 0x00000004"

If you could help me that would be great! Thanks for your time! :)

\$\endgroup\$
3
  • \$\begingroup\$ From just quickly looking over this I wonder where you defined ls_Assets? You declared it in the header but apparently did not define it in the cpp file. \$\endgroup\$
    – hhofbaue
    Jul 19, 2013 at 8:58
  • \$\begingroup\$ Sorry, forgot to add that, I did define it (The main post is updated with it now). \$\endgroup\$
    – Connor W
    Jul 19, 2013 at 16:00
  • \$\begingroup\$ Is this from a bad youtube tutorial? \$\endgroup\$
    – Alayric
    Jul 20, 2013 at 15:14

1 Answer 1

3
\$\begingroup\$

Never make your sf::RenderWindow global.

The SFML developer stated that global RenderWindow can cause issues:

Don't declare your RenderWindow in global scope, something happens in its constructor and some internal objects of SFML might not be initialized at this point.

\$\endgroup\$
4
  • \$\begingroup\$ You should elaborate. \$\endgroup\$ Jul 20, 2013 at 17:51
  • \$\begingroup\$ Hope it's better. \$\endgroup\$
    – Alayric
    Jul 20, 2013 at 18:22
  • \$\begingroup\$ Indeed, perfect. A non-expert like me has no way to know that your answer is exactly right without a reference. \$\endgroup\$ Jul 20, 2013 at 18:28
  • \$\begingroup\$ Ok, thanks! I guess I won't be using that tutorial... \$\endgroup\$
    – Connor W
    Jul 21, 2013 at 15:15

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .