Static GLFWwindow * variable for other uses error

I am trying to avoid using global variables for my game I am working on. So I decided to make the GLFWwindow * variable static.

GLFWwindow * getWindow()
{
    static GLFWwindow * window = glfwCreateWindow( 800, 600, "Window Title", NULL, NULL );
    return window;
}

This is the error I get with this:

Initializer element is not a compile-time constant

I can’t make this static and I am not sure of another way of getting other functions to use this. Any ideas?

This is a C++ issue rather than GLFW. Here’s how you resolve this:

GLFWwindow * getWindow()
{
    static GLFWwindow * window = nullptr; // if not using C++11 use NULL or 0.
    if( nullptr == window )
    {
        window  = glfwCreateWindow( 800, 600, "Window Title", NULL, NULL );
    }
    return window;
}

Essentially the static definition must be a compile time constant, so you use nullptr and then initilaize on the first getWindow() call. This is often referred to as a singleton pattern, and it’s worth reading about the pros and cons of this approach.

I am actually using C, but this worked either way.

Note that in C all static variables are implicitly initialised as zero, so the “= nullptr” is redundant.

This is actually one of those times C differs from C++. Compiled as C++ your code would work as intended, as window will get initialised at runtime the first time you call the getWindow function. C does not have this facility, so you must use something similar to @dougbinks’ answer.