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

#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 :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: 

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

Add new comment

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Refresh Type the characters you see in this picture. Type the characters you see in the picture; if you can't read them, submit the form and a new image will be generated. Not case sensitive.  Switch to audio verification.