extern type variablename;
It turns out that extern is a very interesting command that is often not taught in many tutorials when trying to link multiple C++ files and headers together to create one final executable. As I have finally started building my SFML framework for a GUI, I’ve been meaning to separate all my code into logical files such as “init.cpp” or “entity.h” in order to make everything neater.
But what if I want to use variables from another file? How does this work?
This is where “extern” comes in handy.
In SFML, there is such a thing as sf::Texture. This is just an object to hold an image, such as “button.png.” However, say I want to call one of these from an “init.cpp” in my main function in another file. This means I would have to define this specific sf::Texture object in my main file.
Say the sf::Texture has a name “name”:
extern sf::Texture name;
And that’s all it takes! Isn’t that amazing! Boom!
This is very helpful whenever you want to do such a thing.