I’m currently learning about SDL and i want to take all my functions in an other file name functions.hpp and call the functions in my main.cpp but i don’t know how to do that i have trying different things but it doesn’t work :
An example of what i have in my main.cpp:
//The window we'll be rendering to
SDL_Window* gWindow = NULL;
i want to move the init function in an other file but the gWindow and gRenderer make a problem
To be clear: you have a separate source file with your init() function, and the problem is that it can’t see the global variables in main.cpp (gWindow, gRenderer, etc)?
This tells the compiler that these variables exist somewhere, so it’s okay to use them. The linker will figure out where to find them when building the final executable.
(Ideally, this goes in a header and not at the top of a source file, so there’s one copy of this information that various source files can share, so when this list of variables change, you only have to update one place. But you still need the non-extern lines in main.cpp. One’s a declaration, the other is a definition, and the difference is important. One is a note in the card catalog, the other is the actual book on the shelf.)
(Also, if this wasn’t what you were asking, I apologize in advance!)
One thing: is not dangerous to use global variables ?
It can get messy, and working carefully to manage that messiness is a skill programmers develop over time, but it’s extremely rare to see a large program that doesn’t use some globals.
Many programming courses will say things like “global variables are bad, never use them,” and that’s frankly wrong advice. Limit your use of globals, because it’s easy to get lazy and sloppy with them, but they are a useful tool, even in good clean code.
Then you can initialize the content somewhere near your main() function and after that you can pass it forward.
void MyAmazingFunction(Context *ctx) { ... }
int main(...) {
Context ctx;
ctx.renderer = SDL_CreateRenderer(...);
// and so on
MyAmazingFunction(&ctx);
}