# Reference sf::RenderWindow from another source file in SFML

In SFML, How would you be able to reference a window in your main.cpp file to another source file? I want to be able to reference the window made in main.cpp from player.cpp, so I can keep everything organized and not have so much stuff in main.cpp. Any help is greatly appreciated.

Main.cpp

#include "SFML/Graphics.hpp"
#include <iostream>
#include "Player.h"

int main()
{
sf::RenderWindow window;
sf::VideoMode vmode(800, 600, 32);
window.create(vmode, "Test");

PlayerTest(2);

//Game Loop
while (window.isOpen())
{
// REMEMBER TO FIX PLAYER.CPP

sf::Event event;
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
window.close();
}

window.clear();
window.draw(text);
window.display();
}

return 0;
}


Player.h

#ifndef PLAYER_H
#define PLAYER_H

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

void PlayerTest(float speed);

#endif


Player.cpp

#include "SFML/Graphics.hpp"
#include <iostream>
#include "Player.h"

void PlayerTest(float speed) {

sf::RectangleShape square(sf::Vector2f(100, 100));
square.setFillColor(sf::Color::Cyan);

//window from Main.cpp I need to reference
while (window.isOpen())
{
if (sf::Keyboard::isKeyPressed(sf::Keyboard::W)) {
square.move(0, -speed);
}
else if (sf::Keyboard::isKeyPressed(sf::Keyboard::S)) {
square.move(0, speed);
}
else if (sf::Keyboard::isKeyPressed(sf::Keyboard::A)) {
square.move(-speed, 0);
}
else if (sf::Keyboard::isKeyPressed(sf::Keyboard::D)) {
square.move(speed, 0);
}

//Window from Main.cpp I need to reference
window.clear();
window.draw(square);
window.display();
}
}

• You might want to read a basic C++ tutorial. Why not simply pass the window instace as a reference or a pointer to the PlayerTest function? Anyways I don't feel like this is gamedev specific. Your generic game flow looks also quite wrong, as you have two while loops after each other.
– user35344
Sep 18 '16 at 20:58
• @Tyyppi_77 Thanks for the help, I'm kind of new to C++ and I'll read up again on some tutorials I have. Sep 18 '16 at 21:25

Have your main.cpp call an object Game. This Game object contains everything else. Your game first initializes the Window, then passes the reference to Player when it initializes it.