C++ - OpenGL - Hello World!

After installing the OpenGL libraries on your system, you would definitely want to display something on the screen.

You are right!

So let's see this with an Hello World! OpenGL 2.1 tutorial.

This is really a basic code to display a window and saying: "Great I can do it".
Such basic that it seems C implementation (indeed we don't have any class in this example).

Code

// badprog.com
#include <GL/glut.h>

void displayMe(void)
{
    glClear(GL_COLOR_BUFFER_BIT);
    glBegin(GL_POLYGON);
        glVertex3f(0.0, 0.0, 0.0);
        glVertex3f(0.5, 0.0, 0.0);
        glVertex3f(0.5, 0.5, 0.0);
        glVertex3f(0.0, 0.5, 0.0);
    glEnd();
    glFlush();
}

int main(int argc, char** argv)
{
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_SINGLE);
    glutInitWindowSize(300, 300);
    glutInitWindowPosition(100, 100);
    glutCreateWindow("Hello world from Badprog.com :D");
    glutDisplayFunc(displayMe);
    glutMainLoop();
    return 0;
}

Compiling

g++ main.cpp -o lookAtThis -lglut ; ./lookAtThis

Result

A black window with a white square displayed.

It was your first OpenGL window, you made it.
Great job! laugh

Comments

Comment: 

Thanks, this was the first link with the source code completed and not broken over several pages.

Comment: 

Hello. You might need to compile with -lGL too.

Comment: 

Thanks for the -lGL.

Comment: 

Hi, I think if you add the -lGLU -lGL flags at the end of your compile command this would be a perfect tut

Comment: 

I think you compiling command is not complete:
Following at least is required with a basic installation:
g++ main.cpp -lGL -lGLU -lglut -o myApp

Add new comment

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.