Skip to content
systemcoding.dev
GPU

Request an OpenGL 4.1 core context with glfwWindowHint

Request an OpenGL 4.1 core context with glfwWindowHint before glfwCreateWindow so the profile and version are fixed at creation in GLFW 3.4.

1 min read
Summarize in AI

A GLFW window's OpenGL version and profile are fixed when it is created, so the hints must come first. Version 4.1 is the highest that works on macOS as well as on Windows and Linux.

context.cc
#include <GLFW/glfw3.h>
#include <stdio.h>

int main(void) {
    if (!glfwInit()) return 1;
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 1);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
#ifdef __APPLE__
    glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GLFW_TRUE);
#endif
    GLFWwindow *w = glfwCreateWindow(1280, 720, "gl", NULL, NULL);
    if (!w) { fprintf(stderr, "no 4.1 core context\n"); glfwTerminate(); return 1; }
    glfwMakeContextCurrent(w);
    printf("%d.%d core\n", glfwGetWindowAttrib(w, GLFW_CONTEXT_VERSION_MAJOR),
                           glfwGetWindowAttrib(w, GLFW_CONTEXT_VERSION_MINOR));
    return 0;
}
Text
4.1 core

The version hints are minimums, not exact: the GLFW window guide says the driver may give a newer compatible version, so read the attributes back as above. Asking for a version the driver lacks makes glfwCreateWindow return NULL.

Do not create a context without glfwMakeContextCurrent, or every GL call fails.

Share

More snippets

GPU

List platforms with clGetPlatformIDs

Call clGetPlatformIDs twice, once for the count and once for the handles, then print each platform name with clGetPlatformInfo in OpenCL 3.0 C.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.