# Accessing struct in glut

I have to write a game for a uni project using openGL / glut. I am just going to use a generic example code as I'm just looking for a solution to one specific problem:

Using glut, I have to call a function 'glutDisplayFunc(display);' in the main function. I am also using an IdleFunc(update). The problem is that, as described here, the 'display' function cannot pass anything. I have some structs outside my main that I wish to be initialized in the main, and be accessible by display and update. Hopefully some code will explain my problem better:

#include <gl/glut.h>

struct Player
{
GLfloat x;
GLfloat y;
GLfloat z;
int score;
...
}

//function prototypes (showing how I would normally pass the struct)
void InitPlayer         (Player &player);
void DrawPlayer         (Player &player);
void UpdatePlayer           (Player &player);

void main (int argc, char **argv)
{

Player player;

InitPlayer(player);

//...
//glut / openGL initialisation code left out
//...

glutDisplayFunc         (display);
glutReshapeFunc         (reshape);
glutIdleFunc            (update);

glutMainLoop();

}

void display()
{
DrawPlayer(player);
}

void update ()
{
UpdatePlayer(player);
glutPostRedisplay ();
}
//end


The above code doesn't work: I hope it demonstrates what I would like to do though. Access the struct 'player' in 'display' and 'update', having the same values stored globally. How would I go about ?

First of all, you should be more descriptive about why something doesn't work. At the very least, explain whether it compiles and what errors or bad behavior you are experiencing.

Make player a global object (declared outside of main) and you should be good to go.

• I can't believe I didn't even think of putting 'Player player;' outside the main.. thanks. There wasn't any bad behaviour or compilation errors as such, I just couldn't access variables in the functions I needed. Sorted now, thank you – user15451 Apr 17 '12 at 16:35
• Feel free to upvote and/or mark one of these answers as correct... I'd say either one is "correct." – notlesh Apr 17 '12 at 17:17

A function can only access two things (a member function can access 3, but you can't use them as GLUT callbacks): its parameters and any globally-accessible data. The parameters to your display function can't provide you the information. Therefore, the only alternative is to make whatever your display function needs to access globally accessible.

It's not the cleanest of coding, but that's what happens when you use GLUT. Best accept it and move on.

• Thank you for this. I'm relatively new to this so thank you for explaining it - I was trying not to use globals but it's only a small project I guess! It is a shame we have to use glut but I suppose the course is aimed at teaching 3d Graphics so I guess it's useful for that – user15451 Apr 17 '12 at 16:33