Global Variable of struct

Started by
12 comments, last by chosenkill6 12 years, 6 months ago
I am making a program that has a struct at the beginning of it, but i always have to declare an instance of it within a function. How can i make an instance of a struct global so that it can be accessed by any function?
Advertisement
What language? I'm assuming C, in which case can't you just do
structname instancename;
Outside of a function?
How is your struct declared?

What language? I'm assuming C, in which case can't you just do
structname instancename;
Outside of a function?
How is your struct declared?


Its in C++
My program goes like this:
#include <SDL.h>

SDL_Surface *screen = NULL;

struct visual_object
{
float x,y,v_x,v_y;
SDL_Surface *image;
};

visual_object ball;

int main(int argc, char *args[])
{
SDL_Init(SDL_INIT_VIDEO);
screen = SDL_SetVideoMode(800,600,32,SDL_SWSURFACE);
ball.image = IMG_Load("ball.png");
SDL_BlitSurface(ball.image, NULL, screen, NULL);
SDL_Delay(5000);
return 0;
}


I think that it should be loading my image and displaying it for 5 sec but all i get is an empty screen. Compiles fine though...
You forgot to call SDL_Flip

You forgot to call SDL_Flip


Oh my... I should have seen that. Oh well that's why i posted here so that some experienced programmers can help me out. Haha thanks alot man, im still learning SDL
Lol now i feel like a noob :P
In addition, if you ever need to to use the same global variable in *other* C++ files, you would add this line to the other files, or to a header included by the other files:


extern visual_object ball;
Globals are frowned upon. They aren't too bad for small projects, but they don't scale well. In this case, you can pass the visual_object to any function that needs it as a (const and or reference) parameter.
Yeah, I try not to use global variables, but in this case I can't think a workaround
I could pass the struct as an argument but passing it as a formal argument won't change the original value, and I need that to happen
How can I do that?
You can pass a reference or a pointer to the object. This way you can change the original object.
Tht sounds like it would work
I'll just make a pointer then :P
Makes sense
I have a question for all the game programmers tht have answered all my noob questions
How do u know what to use? I know what a pointer is, how come I didn't think to use one? Where can I get a tut that will help me to think of all these workarounds tht you guys are thinking of? I always make things too complex...

This topic is closed to new replies.

Advertisement