Search code examples
c++openglglut

How to get info from main to void?


I have been tasked with using GLUT to ask the user to enter coordinates and display a rectangle. However, I can't seem to get the coordinates from "int main" to "void display".

Here is my code so far:

#include<iostream>
#include<gl/glut.h>

using namespace std;
void display(float yaxis, float xaxis)
{
    glClearColor(1, 1, 1, 1);

    glClear (GL_COLOR_BUFFER_BIT);

    glBegin (GL_QUADS);

    glColor3f(0, 0, 0);

    glVertex2f(yaxis, -xaxis);
    glVertex2f(yaxis, xaxis);
    glVertex2f(-yaxis, xaxis);
    glVertex2f(-yaxis, -xaxis);
    glEnd();

    glFlush();

}
int main(int argc, char** argv)
{
    float xaxis;
    float yaxis;

    cout << "Please enter the co-ordinates for the x axis and press enter.";
    cin >> xaxis;
    cout << "You entered: " << xaxis
            << ".\n Please enter the co-ordinates for the y axis and press enter.";
    cin >> yaxis;
    cout << "You entered: " << yaxis << ".\n Here is your rectangle.";

    glutInit(&argc, argv);

    glutInitWindowSize(640, 500);

    glutInitWindowPosition(100, 10);

    glutCreateWindow("Triangle");

    glutDisplayFunc(display);

    glutMainLoop();
    return 0;
}

Solution

  • glutDisplayFunc function has the following declaration:

    void glutDisplayFunc(void (*func)(void));
    

    Therefore you can't use your display function as you implemented it. Here is an quick example that can fix your error:

    #include<iostream>
    #include<gl/glut.h>
    
    using namespace std;
    static float yaxis;
    static float xaxis;
    void display()
    {
        glClearColor(1, 1, 1, 1);
    
        glClear (GL_COLOR_BUFFER_BIT);
    
        glBegin (GL_QUADS);
    
        glColor3f(0, 0, 0);
    
        glVertex2f(yaxis, -xaxis);
        glVertex2f(yaxis, xaxis);
        glVertex2f(-yaxis, xaxis);
        glVertex2f(-yaxis, -xaxis);
        glEnd();
    
        glFlush();
    
    }
    int main(int argc, char** argv)
    {
        cout << "Please enter the co-ordinates for the x axis and press enter.";
        cin >> xaxis;
        cout << "You entered: " << xaxis
                << ".\n Please enter the co-ordinates for the y axis and press enter.";
        cin >> yaxis;
        cout << "You entered: " << yaxis << ".\n Here is your rectangle.";
    
        glutInit(&argc, argv);
    
        glutInitWindowSize(640, 500);
    
        glutInitWindowPosition(100, 10);
    
        glutCreateWindow("Rectangle");
    
        glutDisplayFunc(display);
    
        glutMainLoop();
        return 0;
    }