Search code examples
c++functionsfml

RenderWindow not working across multiple functions


I'm new to SFML, and have been watching a tutorial that puts everything in a single main function. When making my own program, I tried to split it into multiple functions, but it isn't working properly, can anyone explain why this works:

#include <SFML/Graphics.hpp>
#include <iostream>

    int main()
    {
        sf::RenderWindow window(sf::VideoMode(512, 512), "window", sf::Style::Resize | sf::Style::Close);
        while (window.isOpen())
    {
        sf::Event evnt;
        while (window.pollEvent(evnt))
        {
            if (evnt.type == evnt.Closed)
            {
                window.close();
            }
        }
        window.clear();
        window.display();
    }
    return 0;
}

and this doesn't:

#include <SFML/Graphics.hpp>
#include <iostream>

sf::RenderWindow window;

void setup()
{
    sf::RenderWindow window(sf::VideoMode(512, 512), "window", sf::Style::Resize | sf::Style::Close);
}

int main()
{
    setup();
    while (window.isOpen())
    {
        sf::Event evnt;
        while (window.pollEvent(evnt))
        {
            if (evnt.type == evnt.Closed)
            {
                window.close();
            }
        }
        window.clear();
        window.display();
    }
    return 0;
}

They will both compile and run, but in the former, the window will stay open, and in the latter, it won't.


Solution

  • The window variable that you've declared inside setup() is shadowing the global window. object. Try the following:

    void setup()
    {
        window.create(sf::VideoMode(512, 512), "window", sf::Style::Resize | sf::Style::Close);
    }