Abhijit Joshi

ENGINEER. PROGRAMMER. ARTIST.

OpenGL Tutorial 001: Opening a GLFW window

In this very first tutorial, we learn how to open a window using GLFW. This is the canvas on which OpenGL will render 2D and 3D images.

You will be able to specify the size of the window (width and height) and give the window a title.

The window remains on the screen until you dismiss it using the mouse or hit Ctrl-C in the terminal.

In subsequent tutorials, we will use OpenGL to render something inside the GLFW event loop and actually draw something in the window. Create a file called openWindow.cpp and copy and paste the code below.


#include <GLFW/glfw3.h>

int main(void)
{
    // initialize GLFW
    glfwInit();

    // set window properties 
    GLFWwindow *window = glfwCreateWindow(640,               // width
                                          480,               // height
                                          "My GLFW window",  // title
                                          NULL,              // use window mode (not full screen)
                                          NULL);             // don't share resources

    // make the windows context current
    glfwMakeContextCurrent(window);

    // GLFW event loop
    while(!glfwWindowShouldClose(window))
    {  
        // OpenGL rendering happens here

        glfwPollEvents();  // watch out for events like mouse clicks, pressed keys etc
    }

    // GLFW clean up
    glfwDestroyWindow(window);
    glfwTerminate();

    return 0;
}

To compile this code, use the Mac-specific Makefile copied below. This will need to be modified for other operating systems. For Macs, we need to link this against several frameworks, as seen below. Remember to use tabs inside the Makefile!


NAME = openWindow

all:
    g++ -I /usr/local/include/ -L /usr/local/lib ${NAME}.cpp -o ${NAME}.x \
    -framework OpenGL \
    -framework Cocoa \
    -framework IOKit \
    -lglfw

clean:
    rm *.x