Fact-checked by Grok 2 weeks ago

GLFW

GLFW is an open-source, cross-platform library written in C that provides a simple application programming interface (API) for creating windows with , , and rendering contexts, as well as handling input and events in graphics applications. It supports major desktop operating systems including Windows, macOS, and via both the X11 and display protocols. Originally developed starting in 2002 by Marcus Geelnard, the project transitioned to maintenance by Camilla Berglund in 2006 and has since been supported by a global community of contributors. Key versions include GLFW 2.0 released in February 2002, which introduced multi-threading and window controls, and the major overhaul in version 3.0 in 2013 that adopted a handle-based with enhanced functions. The latest stable release, version 3.4 from February 2024, adds features such as runtime platform selection and custom memory allocators while maintaining backward compatibility. GLFW is licensed under the permissive zlib/libpng license, allowing free use, modification, and distribution in both open-source and commercial projects. Notable features encompass support for multiple windows and monitors, high-DPI rendering, via ramps, and input handling for keyboards, mice, gamepads, and timers through either polling or callback mechanisms. The library includes comprehensive documentation, tutorials, and examples, along with community-maintained bindings for languages such as , , and .

Overview and History

Introduction

GLFW is a free, open-source, multi-platform library designed for creating windows with , , and contexts, as well as managing input and events in graphics applications. It serves as a lightweight utility that abstracts low-level platform-specific operations, enabling developers to focus on higher-level graphics programming without handling the intricacies of window systems or input devices directly. The library finds primary use in , game development, and interactive applications where rendering with APIs like or is central. Key design principles emphasize simplicity—such as requiring only two function calls to create a and its associated —cross-platform portability across environments, and a deliberate avoidance of graphics rendering tasks to complement specialized libraries like . Implemented in C for broad compatibility and performance, GLFW relies on community-maintained bindings for integration with other programming languages. Over time, it has evolved from supporting earlier graphics standards to incorporating modern APIs like , maintaining its core focus on accessibility and reliability.

Development History

GLFW originated in 2002 as a lightweight, multi-platform library designed for windowing and input handling, providing a simpler alternative to more comprehensive toolkits like GLUT and . The project was initiated by Marcus Geelnard, its original author and initial maintainer, with version 1.0 released that year initially supporting only Windows, followed by additions like X11 support in subsequent minor updates. The 2.x series began with version 2.0 in February 2002, establishing GLFW as a legacy-focused solution primarily for applications, with enhancements over the years including multi-threading, image loading, and platform ports like in version 2.7 (2007). This era emphasized core window and context management without broader multimedia features found in alternatives. A major transition occurred with the release of GLFW 3.0 on June 12, 2013, which overhauled the to support modern graphics development, introducing features like multiple windows and monitors via GLFWwindow and GLFWmonitor objects while removing the legacy threading . Subsequent versions in the 3.x series expanded capabilities; for instance, integration was added in 3.2 (June 2, 2016), enabling surface creation and instance extension queries. Key releases in the 3.3 series marked further evolution: version 3.3, released on April 15, 2019, introduced input support, DPI-aware rendering, and Vulkan enhancements for macOS via MoltenVK, alongside improved compatibility building on its initial implementation in 3.1 (). Later, 3.3.9 (December 13, 2023) integrated libdecor for better window decorations, while 3.3.10 (February 21, 2024) addressed bugs in key scanning and compilation, dropping support for outdated toolchains like Visual C++ 2010/2012 and original . The most recent milestone, GLFW 3.4, released on February 23, 2024, added runtime platform selection, a custom heap allocator for , and the ability to query titles, enhancing flexibility across platforms. Following Geelnard's involvement, maintenance shifted to community-driven efforts led by primary maintainer Camilla Berglund, with ongoing contributions coordinated through the project's repository.

Features

Window and Context Management

GLFW's window and context management facilities form the foundation of its , enabling developers to create portable top-level s with associated rendering s for , , or across multiple platforms. The primary mechanism for initiating this process is the glfwCreateWindow function, which accepts parameters specifying the window's width, height, title, an optional monitor for mode, and an optional share window for resource sharing between contexts. This function returns a handle to the created window object upon success or on failure, encapsulating both the window surface and its rendering context in a single . Prior to calling glfwCreateWindow, developers configure window attributes through glfwWindowHint, allowing customization of properties such as resizability (GLFW_RESIZABLE), decoration visibility (GLFW_DECORATED), and the client type (e.g., GLFW_OPENGL_API for , GLFW_OPENGL_ES_API for , or GLFW_NO_API for -only usage). These hints ensure the window aligns with application requirements while maintaining default behaviors like initial visibility and focus where appropriate. Context management in GLFW revolves around associating rendering with windows and making them active for drawing operations. The glfwMakeContextCurrent function binds a specified window's context to the calling thread, rendering it the current for subsequent API calls from libraries like or ; passing NULL detaches the current . GLFW permits multiple windows and thus multiple per thread, with glfwGetCurrentContext allowing retrieval of the active handle for verification. For resource sharing, such as textures or buffers between , the share parameter in glfwCreateWindow references another window whose objects will be shared, provided both use compatible versions and profiles set via hints like GLFW_CONTEXT_VERSION_MAJOR and GLFW_OPENGL_PROFILE. In scenarios, no is created when GLFW_NO_API is hinted, allowing direct integration with surfaces without interference. Certain GLFW functions, including input queries, require a current and will generate errors otherwise, enforcing thread-local usage. Monitor handling supports multi-display configurations by providing functions to enumerate and interact with available screens. The glfwGetMonitors function returns an of monitor handles representing all connected displays, while glfwGetPrimaryMonitor identifies the main for default fullscreen targeting. windows are created by passing a monitor handle to glfwCreateWindow, automatically adjusting to the monitor's and restoring the original video mode upon destruction. This setup accommodates screen arrangements, where monitors may form extended desktops, enabling applications to position windows across displays seamlessly. To address high-DPI displays, GLFW distinguishes between logical sizes (in screen coordinates) and physical dimensions (in pixels), queried via glfwGetFramebufferSize for accurate rendering scaling. The GLFW_SCALE_TO_MONITOR window hint automatically resizes content based on the attached monitor's content scale factor, ensuring crisp visuals on high-resolution screens without manual intervention. Developers can also retrieve the scale via glfwGetMonitorContentScale for custom adjustments if needed. Window lifecycle concludes with destruction using glfwDestroyWindow, which releases all associated resources, including the rendering , and for fullscreen windows, reverts the monitor to its prior resolution and gamma ramp. Offscreen rendering is supported by creating invisible windows (via GLFW_VISIBLE hint set to GLFW_FALSE) that still provide valid without a visible surface. All remaining windows are automatically destroyed when glfwTerminate is called, ensuring clean shutdown.

Input and Event Handling

GLFW provides mechanisms for capturing and processing user input from keyboards, mice, and gamepads through a combination of polling current states and registering callbacks for events. This dual approach allows developers to choose between querying input at fixed intervals for simplicity or responding immediately to changes for responsiveness in interactive applications. Input handling relies on the maintained by GLFW, which is processed using functions like glfwPollEvents() to update internal states and invoke registered callbacks. Keyboard input in GLFW supports both polling and event-driven methods. The glfwGetKey() function polls the current state of a specified key, returning values such as GLFW_PRESS, GLFW_RELEASE, or GLFW_REPEAT for held keys, enabling straightforward checks in game loops. For event-based handling, glfwSetKeyCallback() registers a callback invoked on key events, providing the key code, scancode, action (press, release, or repeat), and modifier flags like shift or control. This callback model ensures no events are missed, unlike polling which may require frequent queries to avoid lag. Text input is handled separately via glfwSetCharCallback(), which delivers code points for character entry. Mouse input follows a similar pattern, with position tracking via glfwGetCursorPos() to retrieve the cursor's screen coordinates relative to the . Button states are polled using glfwGetMouseButton(), which reports press, release, or repeat actions for each . Event callbacks include glfwSetMouseButtonCallback() for button presses and releases, passing the button, action, and modifiers, and glfwSetCursorPosCallback() for position changes. Scroll events are captured through glfwSetScrollCallback(), delivering horizontal and vertical offsets for or trackpad input. Cursor modes such as GLFW_CURSOR_DISABLED can lock the cursor for unrestricted movement in first-person applications, with raw motion support on compatible platforms. Gamepad support in GLFW is implemented through joystick functions, treating gamepads as a subset of joysticks with standardized mappings. Joysticks are enumerated using glfwGetJoystickName() to identify connected devices by name and presence via glfwJoystickPresent(). Axis and button states are polled with glfwGetJoystickAxes() and glfwGetJoystickButtons(), returning arrays of float values for axes (e.g., thumbsticks) and byte states for buttons. The glfwGetGamepadState() function provides a unified GLFWgamepadstate structure for gamepads with standard mappings from the SDL_GameControllerDB, simplifying access to axes and buttons without manual mapping. Connection and disconnection events are notified via glfwSetJoystickCallback(). Haptic feedback, such as rumble, is not supported in GLFW. The event-driven model in GLFW extends to window-related events beyond input, with callbacks like glfwSetWindowCloseCallback() for close requests, glfwSetWindowSizeCallback() for resizes, and glfwSetWindowFocusCallback() for changes, allowing applications to respond dynamically. These callbacks are triggered during event processing, which synchronizes with rendering via glfwSwapBuffers() to align input updates with vertical sync, preventing tearing and ensuring smooth frame rates in real-time scenarios. For non-rendering applications, glfwWaitEvents() blocks until events occur, reducing CPU usage compared to continuous polling. Polling and callbacks offer distinct trade-offs for performance and responsiveness. Polling via functions like glfwGetKey() or glfwGetMouseButton() is simpler to implement in main loops but can consume more CPU if overused and risks missing transient without sticky key modes (GLFW_STICKY_KEYS). Callbacks, in contrast, provide immediate notification with lower overhead, ideal for applications like games, though they require careful state management to avoid reentrancy issues. Developers typically combine both: polling for continuous state checks and callbacks for discrete , processed after each frame swap to maintain synchronization.

Additional Capabilities

GLFW provides gamma and capabilities through functions that allow applications to adjust output for precise color rendering. The glfwSetGamma generates a gamma ramp from a specified exponent and applies it to the , working in with sRGB gamma correction to ensure accurate color representation. For sRGB support, developers can use the GLFW_SRGB_CAPABLE hint during creation, enabling gamma-correct rendering in or contexts without manual ramp adjustments. These features extend to multi- setups, where gamma ramps can be retrieved with glfwGetGammaRamp and set independently on each using glfwSetGammaRamp, allowing synchronization of across displays by applying identical ramps. Integration with modern graphics APIs is facilitated by GLFW's Vulkan support, introduced in version 3.2 in 2016 to enable window surface creation for rendering. The glfwGetRequiredInstanceExtensions function returns the necessary instance extensions, such as VK_KHR_surface, required for creating a presentation surface with glfwCreateWindowSurface, streamlining the setup process by dynamically loading the loader at runtime. For , extension loading occurs implicitly upon context creation with glfwCreateWindow, making extensions available for querying via glfwExtensionSupported, which checks support for specific extensions like GL_ARB_gl_spirv. Function pointers for these extensions can then be retrieved using glfwGetProcAddress, often in conjunction with loader libraries like GLAD. Version 3.4, released on February 23, 2024, introduced additional features enhancing flexibility and platform support. These include runtime platform selection via the GLFW_PLATFORM initialization hint, allowing developers to choose backends such as or X11 dynamically, and support for custom memory allocators through glfwInitAllocator and the GLFWallocator structure. New window hints like GLFW_MOUSE_PASSTHROUGH enable mouse input to pass through to underlying windows, while expanded cursor shapes (e.g., GLFW_RESIZE_ALL_CURSOR, GLFW_NOT_ALLOWED_CURSOR) and the GLFW_CURSOR_CAPTURED mode improve user interface interactions. integration was further refined with glfwInitVulkanLoader for custom loaders and backend selection via GLFW_ANGLE_PLATFORM_TYPE. -specific enhancements include support for glfwRequestWindowAttention, fractional scaling, and the GLFW_WAYLAND_APP_ID hint for application identification. These updates maintain while addressing modern development needs as of November 2025. Utility functions enhance GLFW's versatility for additional tasks beyond core windowing. Clipboard operations are handled by glfwSetClipboardString, which sets the system clipboard to a UTF-8 encoded string, and its counterpart glfwGetClipboardString for retrieval, enabling seamless data exchange in applications. High-resolution timing is provided by glfwGetTime, which returns the elapsed time in seconds since library initialization with microsecond or nanosecond precision, while glfwSetTime allows resetting the timer base for custom timing needs. Joystick input extends to hat states, representing directional pads, queried via glfwGetJoystickHats, which returns an array of unsigned char values indicating positions like centered, up, down, left, right, or diagonals using bitwise combinations.

Architecture

Core Implementation

GLFW is implemented as a lightweight, portable library utilizing a subset of the standard, ensuring compatibility across various compilers such as and Visual C++ 2013 through 2022. This choice emphasizes portability and simplicity, with the core functionality relying solely on the for operations like memory allocation, avoiding any external dependencies to maintain a small footprint and ease of integration into diverse projects. The library's design prioritizes minimalism, loading graphics APIs such as , , or at runtime without compile-time linkages, further reducing overhead. The core architecture adopts a modular approach, distinctly separating concerns into dedicated categories for management, input handling, and rendering creation, which facilitates targeted use and straightforward extension without affecting unrelated components. For instance, -related functions like glfwCreateWindow operate independently of input polling routines such as glfwPollEvents, allowing developers to leverage only the necessary subsets for their applications. This separation enhances and , as each module abstracts platform-specific details into a unified while keeping the internal state encapsulated. Error handling in GLFW is robust and developer-friendly, centered on a callback mechanism via glfwSetErrorCallback, which allows applications to register a custom function that receives an error code and description whenever an issue arises, such as invalid arguments or resource failures. Complementing this, the glfwGetError function enables querying the last error code, including specific enumerations like GLFW_NOT_INITIALIZED (0x00010001), which signals attempts to use library functions before proper setup, promoting reliable debugging without halting execution. These mechanisms ensure errors are communicated clearly, with codes covering scenarios from memory exhaustion (GLFW_OUT_OF_MEMORY) to unavailability (GLFW_API_UNAVAILABLE), all while maintaining the library's non-intrusive nature. Initialization forms the foundation of GLFW's operation, triggered by a single call to glfwInit(), which establishes the library's internal state, including and platform detection, returning GLFW_TRUE on success or GLFW_FALSE otherwise. This process sets up global configurations, such as hints for subsequent operations via glfwInitHint, and must precede all other library usage to avoid errors like GLFW_NOT_INITIALIZED. Cleanup is symmetrically handled by glfwTerminate(), which systematically destroys any created windows, cursors, and contexts, restores system settings like gamma ramps, and releases all allocated resources, ensuring no lingering effects upon application exit. Developers can optionally specify a memory allocator with glfwInitAllocator prior to initialization for tailored . Regarding concurrency, GLFW enforces a threading model that requires all window creation, destruction, initialization, termination, and event processing to occur on the —the one invoking the program's —due to inherent platform constraints. Post-initialization, limited multi-threading is supported for non-window operations, such as querying input states or error codes from secondary threads, though the library provides internal synchronization only for context and error states, leaving broader application-level coordination to the user. Callbacks, excluding the error handler, are guaranteed to execute solely on the , reinforcing this model to prevent race conditions in core operations while allowing flexible input handling in multi-threaded environments.

Programming Language Bindings

GLFW provides a native C API that serves as the reference implementation for all language bindings, with no official bindings developed or maintained by the GLFW project itself. Instead, the project relies on community contributions for wrappers in other programming languages, as documented on the official GLFW community page. These bindings enable developers to access GLFW's window management, input handling, and OpenGL context creation functionalities from higher-level or alternative languages, often through foreign function interfaces (FFI) that bridge the C-based core. Among the most popular community-maintained bindings are those for , , , and Go. For , GLFW.jl offers a comprehensive interface that wraps the full , allowing seamless integration with Julia's ecosystem for tasks like creation and polling. In , the glfw package provides a ctypes-based wrapper that closely mirrors the original C , supporting without requiring , while pyGLFW serves as an alternative CFFI implementation for similar purposes. Rust developers commonly use glfw-rs, an idiomatic wrapper built on top of low-level bindings, which handles concerns inherent to while providing access to callbacks and context management. For Go, the go-gl/glfw binding includes GLFW for easy and supports cross-platform handling through Go's cgo mechanism. These bindings, along with over 60 others for languages such as C#, , and , are tracked and updated via community reports on the repository. Creating and maintaining these bindings presents specific challenges, particularly in handling GLFW's C-style pointers, error codes, and callback functions across language boundaries. Callbacks for events like key presses or window resizes require FFI mechanisms to pass function pointers safely, often necessitating workarounds in object-oriented or garbage-collected languages to avoid issues like dangling references or non-static member functions, as noted in GLFW's input guide and common binding implementations. For instance, languages without direct pointer support must emulate opaque handles or use closures, which can introduce overhead or compatibility issues during library updates. Despite these hurdles, bindings like those for C++ achieve full feature parity simply by including GLFW's C headers in C++ projects, as the API is designed to be compatible with C++ compilers without additional wrappers. In terms of usage, C and C++ applications typically involve direct static or dynamic linking to the GLFW library after including the header file, enabling straightforward calls to functions like glfwCreateWindow. Scripting languages, such as Python or Lua, leverage dynamic loading through their respective FFI tools—ctypes in Python or FFI libraries in Lua—to invoke GLFW without building native extensions, facilitating rapid prototyping but potentially at the cost of performance. Maintenance of these third-party bindings varies: some, like glfw-rs and GLFW.jl, are actively developed with regular updates to match GLFW releases, while others may lag in feature completeness or platform support, requiring users to verify compatibility against the core C API. Developers are encouraged to contribute to or report issues for these bindings via their respective repositories to ensure ongoing viability.

Platform Back-ends

GLFW's platform back-ends provide the low-level integrations necessary for its cross-platform functionality, abstracting operating system-specific APIs to create windows, manage and contexts, handle input, and support timing mechanisms. These back-ends are implemented in platform-specific directories within the GLFW , ensuring portability while leveraging native capabilities for and compatibility. On Windows, the back-end utilizes the Win32 API for window creation and management, enabling features like fullscreen modes and monitor enumeration through functions such as GetDC for device contexts. contexts are handled via the WGL extension, which allows for advanced context attributes like multisampling and core profiles. For input, particularly joysticks, it employs alongside XInput, replacing earlier reliance on WinMM for more robust support introduced in version 3.0. The macOS back-end is built on the framework, using NSWindow and NSView for window handling, which supports scaling and native menu integration. OpenGL contexts are created with NSOpenGLContext, providing access to hardware-accelerated rendering up to 4.1 on compatible hardware. Timing precision is achieved through Core Video's CVDisplayLink, which synchronizes with the display refresh rate for smooth event polling and rendering. For systems using X11, the back-end relies on Xlib or XCB for display server communication, facilitating window properties, events, and multi-monitor setups via extensions like XRandR. serves as the interface for context management, supporting FBConfig for precise pixel format selection. Input events, including and , are captured through evdev, the Linux input subsystem, allowing direct access to device nodes for low-latency handling. Wayland support was introduced in GLFW 3.2, utilizing the libwayland-client library to interface with the compositor protocol for window surfaces and output management. This enables native applications without XWayland fallback, though early versions had limitations in decorations and input focus. Starting with version 3.3.9, libdecor integration provides client-side decorations, rendering window borders and controls within the application for better compatibility with compositors lacking server-side decorations. GLFW 3.4 introduced runtime platform selection, allowing a single binary to dynamically choose between available back-ends like X11 and on without recompilation. This is controlled via the GLFW_PLATFORM hint, defaulting to GLFW_ANY_PLATFORM, with support queried through glfwPlatformSupported and the selected platform retrieved via glfwGetPlatform. This feature enhances deployment flexibility, especially in environments where both protocols coexist.

Supported Platforms

Desktop Platforms

GLFW officially supports a range of operating systems, providing cross-platform windowing and input capabilities for graphics applications. These platforms utilize distinct back-ends for window management and context creation, as detailed in the section. On Windows, GLFW offers support starting from and later, maintaining full compatibility with and 11, enabling robust and context creation through the Win32 API. For macOS, compatibility begins with version 10.8 (Mountain Lion) and extends to the latest releases, up to macOS 15 and later versions as of November 2025; contexts are created using the framework and NSOpenGL. Linux and other systems support, including and , encompasses X11 on major distributions such as 18.04 and later, alongside in and environments, with compositors implementing the xdg-shell protocol for seamless integration. Unlike broader libraries such as , GLFW does not extend official support to mobile or embedded systems, including or , concentrating instead on desktop environments. Earlier iterations of GLFW included experimental X11 support on macOS via , but this has been deprecated in favor of the native back-end in recent versions.

Compatibility and Requirements

GLFW requires compilers that support the standard, as the library is implemented using C99 features. On Windows, it is tested and supported with Visual Studio 2013 and later versions, with binaries for Visual C++ 2010 and 2012 discontinued starting from version 3.3.10 due to lack of support for those compilers. For cross-platform development, or via is recommended, ensuring compatibility across systems and Windows. The library maintains minimal dependencies to facilitate easy integration, with no mandatory external libraries required beyond standard platform development tools. On systems, building for X11 necessitates X11 development packages such as libXrandr and libXi, while builds require libwayland and libxkbcommon; however, these are platform-provided and not additional burdens. Optionally, libdecor can be used for enhanced client-side window decorations on , enabled via the GLFW_WAYLAND_LIBDECOR option since version 3.3.9, but it is not essential for core functionality. At runtime, GLFW demands a graphics driver supporting OpenGL 2.1 or higher for desktop contexts, or OpenGL ES 2.0 for embedded systems, with the ability to request higher versions like OpenGL 3.0 core by default if available. Vulkan support, introduced for surface creation, requires a system-wide Vulkan 1.0 loader and compatible instance extensions such as VK_KHR_surface, along with platform-specific extensions like VK_KHR_win32_surface on Windows. Any GPU with up-to-date drivers meeting these API levels suffices, though advanced features like gamma control or multisampling depend on extensions such as GLX_MESA_swap_control on X11. Building GLFW supports both static and dynamic linking via , the recommended cross-platform build system, where the GLFW_LIBRARY_TYPE option allows selection of STATIC, SHARED, or OBJECT libraries. Static linking embeds GLFW directly into applications, ideal for distribution without DLL dependencies, while dynamic linking reduces binary size but requires runtime library presence. generates project files for IDEs like or makefiles for Unix, with platform back-ends (e.g., Win32, , Wayland, X11) configurable at build time. Certain limitations affect compatibility, particularly on non-x86 architectures and legacy configurations. Official desktop builds lack native support, requiring custom ports or cross-compilation for platforms like , though the source can be adapted for ARM Linux with appropriate toolchains. High-DPI scaling may encounter issues on older X11 setups without XRandR 1.3, potentially leading to incorrect monitor resolution detection or framebuffer scaling.

Usage

Initialization and Setup

To initialize GLFW for application development, the process begins with setting up an error callback using glfwSetErrorCallback, which registers a to handle error notifications from the library. This callback receives an and a human-readable description, allowing developers to capture issues such as version mismatches or initialization failures before or during the setup phase. It is recommended to install this callback prior to any other GLFW calls, as errors can occur on any and the description string remains valid only until the callback returns. The core initialization step is performed by calling glfwInit(), a single function that prepares the GLFW library for use by checking system capabilities, enumerating connected monitors, and initializing the internal timer. This function takes no parameters and returns GLFW_TRUE on success or GLFW_FALSE on failure, in which case partial cleanup is automatically performed and no further GLFW functions should be used until reinitialization. It must be invoked from the main thread and sets default configuration hints, establishing the foundation for subsequent operations like window creation. After initialization, developers can query the runtime version of GLFW using glfwGetVersion, which populates integer pointers for the major, minor, and revision numbers to enable compatibility checks against the header . Complementing this, glfwGetVersionString returns a static detailing the full , including platform and compiler information, though it is advised not to parse this for numbers—instead, rely on the integer query for precision. These queries can be called at any time, even before initialization, to verify library compatibility in the application environment. Configuration of library and window properties occurs through hints set using glfwInitHint before glfwInit for library-wide settings, or glfwWindowHint before window creation for window-specific attributes such as GLFW_VISIBLE to control initial window visibility or GLFW_SAMPLES to specify multisampling levels for . These hints are integers passed as hint-value pairs and must be set before creating a window, as they influence its properties without altering the core library state. Default values are applied during initialization if not overridden, ensuring a standard setup unless customized. Proper cleanup is achieved by calling glfwTerminate() at application exit, which releases all allocated resources, destroys any remaining windows and cursors, and restores system settings like gamma ramps to their original state. This function takes no parameters, has no return value, and is safe to invoke even if GLFW was never initialized, making it essential for resource management in long-running or error-prone programs. Following termination, reinitialization is possible, though typically unnecessary.

Basic Programming Example

A minimal GLFW application in C creates a , sets up basic input handling, and enters a rendering loop. The following self-contained example initializes GLFW, opens a 640x480 titled "Minimal GLFW Example", registers a key callback to close the on ESC press, and runs a main loop that processes events and swaps buffers until the is closed.
c
#include <GLFW/glfw3.h>

static void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods)
{
    if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)
        glfwSetWindowShouldClose(window, GLFW_TRUE);
}

int main(void)
{
    GLFWwindow* window;

    if (!glfwInit())
        exit(EXIT_FAILURE);

    window = glfwCreateWindow(640, 480, "Minimal GLFW Example", NULL, NULL);
    if (!window)
    {
        glfwTerminate();
        exit(EXIT_FAILURE);
    }

    glfwSetKeyCallback(window, key_callback);

    while (!glfwWindowShouldClose(window))
    {
        glfwPollEvents();
        glfwSwapBuffers(window);
    }

    glfwDestroyWindow(window);
    glfwTerminate();
    exit(EXIT_SUCCESS);
}
This code begins by including the GLFW header and defining a key callback function that checks for the ESC key press and signals the window to close. Initialization occurs with glfwInit(), followed by window creation using glfwCreateWindow() with specified dimensions and title; error checking ensures successful setup before proceeding. The key callback is then registered with glfwSetKeyCallback(). The main loop, structured as while (!glfwWindowShouldClose(window)), continuously calls glfwPollEvents() to process pending input and window events, followed by glfwSwapBuffers() to update the display—serving as a placeholder for rendering operations in a full application. Cleanup involves destroying the window and calling glfwTerminate() to release resources. To compile this example on systems, use a command such as cc -o example example.c $(pkg-config --cflags --libs glfw3) for dynamic linking, or include -lglfw3 directly if pkg-config is unavailable; on Windows with , link against libglfw3.a or equivalent, such as gcc -o example example.c -lglfw3 -lgdi32. Common pitfalls include neglecting to check return values from glfwInit() or glfwCreateWindow(), which can lead to if initialization fails; additionally, if rendering with is added later, forgetting to call glfwMakeContextCurrent(window) before issuing OpenGL commands will prevent proper context usage, and not handling window resize events may cause display issues. For more advanced input handling, such as or callbacks, refer to the Input and Event Handling section.

Licensing and Community

License

GLFW is licensed under the zlib/libpng , a permissive approved by the (OSI) that is BSD-like in nature. This license grants users the right to use, copy, modify, merge, publish, distribute, sublicense, and sell copies of the software for any purpose, including commercial applications, subject to specific conditions. Key terms of the include providing the software "" without any express or implied warranties, and the licensor disclaims for any arising from its use. Redistributions in or must retain the original , the above list of conditions, and the following . Altered source versions must be plainly marked as such, and binary versions derived from altered source code must reproduce the above , this list of conditions, and the in the and/or other materials provided with the distribution. The copyright notice attributes the original work to Marcus Geelnard for the years 2002–2006 and to Camilla Löwy for 2006–2019, with community contributions integrated under the same license terms. Unlike copyleft licenses such as the GNU General Public License (GPL), the zlib/libpng license permits static linking with closed-source software without requiring the disclosure of the linking application's source code. Both the source code and precompiled binaries for GLFW are distributed under this license, enabling broad adoption in diverse projects.

Development and Maintenance

GLFW is hosted on at the glfw/glfw, where development occurs through issue tracking for bug reports and feature requests, pull requests for code submissions, and release tags marking stable versions since GLFW 3.0. The project has been community-led since the mid-2010s, with core contributors, including primary maintainer Camilla Löwy (formerly Berglund), overseeing merges, reviews, and official releases. Contributions are managed via pull requests, emphasizing adherence to the existing codebase style in , as no formal exists; developers are encouraged to match the prevailing code patterns during submissions. The guidelines stress testing requirements, including the use of provided test programs in the repository's tests directory for verifying functionality across platforms, and prioritize portability to ensure compatibility with Windows, macOS, (including X11 and ), and other systems. Official documentation is maintained on the project website at glfw.org, featuring guides, an API reference, and an , with updates synchronized to new releases to reflect changes in functionality and platform support. Future directions are shaped by community feedback through the forum and GitHub issues, with recent efforts focusing on enhancements like improved support, including runtime platform selection and integration with libraries such as libdecor, as seen in version 3.4; mobile ports remain unexplored in current plans.

References

  1. [1]
    An OpenGL library
    ### Summary of GLFW
  2. [2]
    glfw/glfw: A multi-platform library for OpenGL, OpenGL ES ... - GitHub
    GLFW is an Open Source, multi-platform library for OpenGL, OpenGL ES and Vulkan application development. It provides a simple, platform-independent APIGLFW · Home · glfw/glfw Wiki · Issue tracker · Pull requests 152
  3. [3]
    [PDF] GLFW Reference Manual
    Sep 3, 2010 · c 2002-2006 Marcus Geelnard c 2006-2010 Camilla Berglund. Page 2 ... If neither is available, no other extensions are used and many GLFW features ...
  4. [4]
    Version history | GLFW
    Apr 5, 2013 · This is the complete log of user-visible changes for each version since the project started. For a task oriented view of changes and additions in recent ...
  5. [5]
  6. [6]
  7. [7]
  8. [8]
    Version history
    ### GLFW Development History Summary
  9. [9]
    Isn't SDL the simplest, most portable way to use OpenGL? OpenGL ...
    SDL is a portable OpenGL chassis, but some find it heavy and complex. GLFW is a simpler, smaller alternative, though not available on Android/iOS.<|control11|><|separator|>
  10. [10]
    GLFW 2.7.7 release notes
    GLFW is a free, Open Source, multi-platform library for OpenGL application development that provides a powerful API for handling operating system specific tasks ...Missing: date | Show results with:date
  11. [11]
    Version 3.0 released - GLFW
    Jun 12, 2013 · Version 3.0 released. Posted on June 12, 2013. GLFW 3.0 is available for download. It adds support for multiple windows, multiple monitors, ...
  12. [12]
    Version 3.2 released - GLFW
    Jun 2, 2016 · GLFW 3.2 is available for download. It adds support for Vulkan surface creation, window mode switching, window maximization, window input focus control.
  13. [13]
    Version 3.3 released - GLFW
    Apr 15, 2019 · Version 3.3 released. Posted on April 15, 2019. GLFW 3.3 is available for download. It adds gamepad input via SDL_GameControllerDB, support ...
  14. [14]
    Window guide - GLFW
    This guide introduces the window related functions of GLFW. For details on a specific function in this category, see the Window reference.
  15. [15]
    Context guide - GLFW
    This guide introduces the OpenGL and OpenGL ES context related functions of GLFW. For details on a specific function in this category, see the Context ...
  16. [16]
    Input guide - GLFW
    This guide introduces the input related functions of GLFW. For details on a specific function in this category, see the Input reference.
  17. [17]
    Input reference - GLFW
    This is the reference documentation for input related functions and types. For more task-oriented information, see the Input guide.
  18. [18]
  19. [19]
  20. [20]
  21. [21]
    GLFW: Vulkan guide
    ### Summary of Vulkan Integration in GLFW
  22. [22]
  23. [23]
    GLFW: Building applications
    **Summary of GLFW Build Guide (https://www.glfw.org/docs/3.4/build_guide.html):**
  24. [24]
    FAQ
    ### Summary of GLFW Core Implementation
  25. [25]
    GLFW: Introduction to the API
    ### Summary of GLFW's Core Implementation Aspects
  26. [26]
    GLFW: Error codes
    ### Summary of Error Handling in GLFW (Docs 3.4)
  27. [27]
    GLFW: Initialization, version and error reference
    ### Summary of Initialization: glfwInit, glfwTerminate, Internal State Setup, Cleanup
  28. [28]
    GLFW: Introduction to the API
    ### Summary of GLFW Threading Model
  29. [29]
    Community
    ### Summary of GLFW Language Bindings
  30. [30]
    JuliaGL/GLFW.jl - GitHub
    Julia interface to GLFW 3, a multi-platform library for creating windows with OpenGL or OpenGL ES contexts and receiving many kinds of input.Issues 22JuliaGL/GLFW.jl
  31. [31]
    glfw - PyPI
    Author: Florian Rhiem; Provides-Extra: preview. Classifiers ... It is a ctypes wrapper which keeps very close to the original GLFW API, except for:.
  32. [32]
    FlorianRhiem/pyGLFW: Python bindings for GLFW - GitHub
    This module provides Python bindings for GLFW (on GitHub: glfw/glfw). It is a ctypes wrapper which keeps very close to the original GLFW API, except for:.
  33. [33]
    PistonDevelopers/glfw-rs: GLFW3 bindings and idiomatic ... - GitHub
    GLFW3 bindings and idiomatic wrapper for Rust. Contribute to PistonDevelopers/glfw-rs development by creating an account on GitHub.
  34. [34]
    go-gl/glfw: Go bindings for GLFW 3 - GitHub
    Easy go get installation. GLFW source code is now included in-repo and compiled in so you don't have to build GLFW on your own and distribute shared libraries.
  35. [35]
    Getting started - GLFW
    This guide takes you through writing a small application using GLFW 3. The application will create a window and OpenGL context, render a rotating triangle and ...<|control11|><|separator|>
  36. [36]
  37. [37]
    GLFW: Native access
    ### Summary of Native Access Functions in GLFW (Version 3.4)
  38. [38]
    Version 3.3.9 released - GLFW
    Dec 13, 2023 · Version 3.3.9 released ... This is primarily a bug fix release for all supported platforms but it also adds libdecor support for Wayland.Missing: client | Show results with:client
  39. [39]
    Version 3.4 released - GLFW
    Feb 23, 2024 · It adds runtime platform selection, better support for Wayland, both Wayland and X11 enabled by default, more standard cursor shapes, custom ...
  40. [40]
  41. [41]
    FAQ - GLFW
    GLFW is a small C library that lets you create and manage windows, OpenGL and OpenGL ES contexts and Vulkan surfaces, enumerate monitors and video modes.
  42. [42]
    GLFW: Compiling GLFW
    ### Platform-Specific Requirements and Minimum OS Versions
  43. [43]
    Version 3.3.10 released - GLFW
    Feb 21, 2024 · This is a bug fix release. It adds fixes for issues on all supported platforms. Binaries for Visual C++ 2010 and 2012 are no longer included.
  44. [44]
    GLFW: Standards conformance
    ### Summary of GLFW Compatibility, Requirements, and Limitations
  45. [45]
    is the use of glfw not supported on arm linux?
    Oct 10, 2019 · It looks like Raspberry Pi users have been able to get GLFW working on their arm linux systems by compiling on the target system rather than cross compiling.Missing: desktop | Show results with:desktop
  46. [46]
  47. [47]
    GLFW: Introduction to the API
    ### Summary of GLFW Sections
  48. [48]
  49. [49]
    GLFW: Getting started
    ### Extracted C Programming Example for Minimal GLFW Application
  50. [50]
    License - GLFW
    License. GLFW is licensed under the zlib/libpng license, a BSD-like license that allows static linking with closed source software.
  51. [51]
  52. [52]
    Camilla Löwy elmindreda - GitHub
    elmindreda has 21 repositories available. Follow their code on GitHub.Missing: maintainers | Show results with:maintainers
  53. [53]
    Community - GLFW
    Bindings for other languages are created and maintained by the community and are not part of GLFW itself. Please let us know if one should be added or removed.
  54. [54]
    Double spaces in documentation - support - GLFW
    Feb 19, 2023 · GLFW doesn't have a style guide in the contribution section, and the normal practice when developing PRs is to stick to the style in use. I ...
  55. [55]
    glfw/docs/CONTRIBUTING.md at master · glfw/glfw
    Insufficient relevant content. The provided text from https://github.com/glfw/glfw/blob/master/docs/CONTRIBUTING.md contains only navigation, metadata, and boilerplate text, with no substantive contribution guidelines or details on C code style, testing, portability, pull requests, or merges.
  56. [56]
    Wayland Readiness for 2024+ · Issue #2439 · glfw/glfw - GitHub
    Dec 2, 2023 · This is the plan. Add support for XDG activation and fractional scaling, add various bug fixes and then make a 3.4 release as soon as possible with Wayland as ...Missing: future mobile
  57. [57]