Getting started with GLFW

It’s quite a lot of work to get a window with an OpenGL context on screen in modern operating systems. And if you want to make anything cross-platform, then you need to learn different ways of GUI programming. It’s obviously much better to use a library to get all that stuff out of the way so you can concentrate on just the graphics part of your application.

The OpenGL library I like most at the moment is GLFW. It is very easy to use and not bloated like some other systems. I just want to get an OpenGL window and access to input like keyboard and mouse. I can handle the rest, thank you very much.

So, here is a small “Hello World” example for using GLFW to get something on screen. I won’t tell you how to link libraries or add include directories, you’ll have to find that out for yourself as it highly depends on your OS and IDE. But here is the code for a simple rotating triangle.

Note: This example uses the old deprecated fixed function immediate mode. If you really want to learn OpenGL, you should learn the newer version. I do it this way because it is a LOT less code and is much easier to understand.

#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <stdlib.h>
#include <iostream>

static void keyCallback(GLFWwindow* window, int key, int scancode, int action, int mods)
    if( key==GLFW_KEY_ESCAPE && action==GLFW_PRESS ) // press escape to quit

int main()
    // Initialise GLFW
    if( !glfwInit() ) exit(EXIT_FAILURE);
    // Open GLFW window
    GLFWwindow* window = glfwCreateWindow(640, 480, "Hello World!", NULL, NULL);
    if( !window )
        std::cout << "Cannot open GLFW window\n";
    // Set callbacks here. Just keyboard for now
    glfwSetKeyCallback(window, keyCallback);
    // initialise GLEW
    glewExperimental = GL_TRUE;
    if( glewInit()!=GLEW_OK )
        std::cout << "Cannot initialise GLEW\n";
    while( !glfwWindowShouldClose(window) )
        // Clear the screen. We are not using zbuffer so just clear colours
        // Set up the modelview matrix
        glRotatef(glfwGetTime()*100.f, 0, 1, 0);
        // Draw a triangle
        glColor3f(1,0,0); glVertex2f( 0.0f, 0.5f);
        glColor3f(0,1,0); glVertex2f(-0.5f,-0.5f);
        glColor3f(0,0,1); glVertex2f( 0.5f,-0.5f);
        // Perform double buffering and poll events
    return EXIT_SUCCESS;

Published by


Just a programmer who loves sushi.

Leave a Reply

Your email address will not be published. Required fields are marked *