Add Dear ImGui to a GLFW and OpenGL Application
Add Dear ImGui 1.91 to a GLFW 3.4 and OpenGL 3.3 program in C++, wire the two backends, draw a debug window with sliders, and stop input leaking to the scene.

The first time a graphics program needs a number you can change while it runs, such as a light color, a field of view or a debug toggle, the choices are to recompile for every tweak or to build a user interface. Dear ImGui is a C++ library that makes the second choice cheap. You describe the interface in code, one function call per widget, every frame, and the library produces the triangles to draw it. This post wires Dear ImGui 1.91 into a GLFW 3.4 window with an OpenGL 3.3 core context, draws a window with a slider, a color picker and a checkbox, and handles the one subtle issue: stopping the interface and the scene from fighting over the mouse. It starts from the GLFW window loop.
How ImGui works
Dear ImGui is an immediate-mode library. In a retained-mode toolkit such as Qt you create button objects once and the toolkit remembers them. In immediate mode you call ImGui::Button("Reset") every frame, and the call both draws the button and returns true on the frame it was clicked. Nothing is stored in your code except the variables that widgets edit. That makes small tools fast to write and keeps interface state in plain variables.
The library itself knows nothing about windows or GPUs. It produces a list of vertices and draw commands. Two small adapters called backends connect it to the outside world: a platform backend feeds it mouse, keyboard and window size from GLFW, and a renderer backend draws its output with OpenGL. Both ship in the ImGui repository, in the backends folder.
Get the sources
ImGui is meant to be compiled into your project as source. Clone it next to your code and pin a release:
git clone --branch v1.91.9 https://github.com/ocornut/imgui.git third_party/imguiYou need these files: imgui.cpp, imgui_draw.cpp, imgui_tables.cpp, imgui_widgets.cpp from the root, and backends/imgui_impl_glfw.cpp and backends/imgui_impl_opengl3.cpp. Add them to the build with include directories for the root and backends:
cmake_minimum_required(VERSION 3.20)
project(imgui_demo CXX C)
set(CMAKE_CXX_STANDARD 17)
find_package(glfw3 3.4 REQUIRED)
set(IMGUI_DIR third_party/imgui)
add_library(imgui STATIC
${IMGUI_DIR}/imgui.cpp
${IMGUI_DIR}/imgui_draw.cpp
${IMGUI_DIR}/imgui_tables.cpp
${IMGUI_DIR}/imgui_widgets.cpp
${IMGUI_DIR}/backends/imgui_impl_glfw.cpp
${IMGUI_DIR}/backends/imgui_impl_opengl3.cpp)
target_include_directories(imgui PUBLIC ${IMGUI_DIR} ${IMGUI_DIR}/backends)
target_link_libraries(imgui PUBLIC glfw)
add_library(glad third_party/glad/src/gl.c)
target_include_directories(glad PUBLIC third_party/glad/include)
add_executable(app main.cpp)
target_link_libraries(app PRIVATE imgui glad)The OpenGL backend loads its own function pointers when it initializes, using its bundled loader, so it does not conflict with your glad. If you already include glad, define IMGUI_IMPL_OPENGL_LOADER_CUSTOM and include your loader header before the backend to keep one loader in the program.
The program
The structure has three phases: set up once, run the frame loop, shut down. The ImGui calls sit at fixed places inside the loop:
#include <glad/gl.h>
#include <GLFW/glfw3.h>
#include "imgui.h"
#include "imgui_impl_glfw.h"
#include "imgui_impl_opengl3.h"
int main() {
if (!glfwInit()) return 1;
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
#ifdef __APPLE__
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GLFW_TRUE);
#endif
GLFWwindow* window = glfwCreateWindow(960, 540, "ImGui demo", nullptr, nullptr);
if (!window) { glfwTerminate(); return 1; }
glfwMakeContextCurrent(window);
gladLoadGL(glfwGetProcAddress);
glfwSwapInterval(1);
IMGUI_CHECKVERSION();
ImGui::CreateContext();
ImGuiIO& io = ImGui::GetIO();
io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard;
ImGui::StyleColorsDark();
ImGui_ImplGlfw_InitForOpenGL(window, true);
ImGui_ImplOpenGL3_Init("#version 330");
float clear[3] = { 0.10f, 0.12f, 0.16f };
float fov = 60.0f;
bool wireframe = false;
while (!glfwWindowShouldClose(window)) {
glfwPollEvents();
ImGui_ImplOpenGL3_NewFrame();
ImGui_ImplGlfw_NewFrame();
ImGui::NewFrame();
ImGui::Begin("Controls");
ImGui::Text("Frame time: %.2f ms (%.0f FPS)", 1000.0f / io.Framerate, io.Framerate);
ImGui::SliderFloat("Field of view", &fov, 30.0f, 120.0f);
ImGui::ColorEdit3("Clear color", clear);
ImGui::Checkbox("Wireframe", &wireframe);
if (ImGui::Button("Reset")) {
fov = 60.0f;
clear[0] = 0.10f; clear[1] = 0.12f; clear[2] = 0.16f;
wireframe = false;
}
ImGui::End();
ImGui::Render();
int fw, fh;
glfwGetFramebufferSize(window, &fw, &fh);
glViewport(0, 0, fw, fh);
glClearColor(clear[0], clear[1], clear[2], 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
glPolygonMode(GL_FRONT_AND_BACK, wireframe ? GL_LINE : GL_FILL);
// draw your scene here
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());
glfwSwapBuffers(window);
}
ImGui_ImplOpenGL3_Shutdown();
ImGui_ImplGlfw_Shutdown();
ImGui::DestroyContext();
glfwDestroyWindow(window);
glfwTerminate();
return 0;
}What each ImGui call does
IMGUI_CHECKVERSION() compares the headers you compiled against with the library you linked, and asserts when they differ, which catches a stale include path early. ImGui::CreateContext() allocates the library's global state, and GetIO() returns the struct used for configuration and for reading input state, such as io.Framerate.
ImGui_ImplGlfw_InitForOpenGL(window, true) hooks the platform backend to the window. The true argument tells the backend to install its own GLFW callbacks for keys, characters, mouse and scroll, and to chain to any callbacks you had registered before the call. If you install callbacks of your own after this call, you replace the backend's and ImGui stops seeing input, so register yours first, or pass false and forward events by calling ImGui_ImplGlfw_KeyCallback and friends yourself.
ImGui_ImplOpenGL3_Init("#version 330") initializes the renderer backend with the GLSL version string its internal shaders use. The string must match your context: #version 330 for OpenGL 3.3. The ImGui example code uses #version 150 on macOS, whose core profile is a forward-compatible 3.2 context, so match the string to the context you actually requested.
The three calls at the top of the loop start a new ImGui frame: the two backends read the mouse and window size, and ImGui::NewFrame() begins recording widgets. Everything between NewFrame and Render is your interface. ImGui::Render() finishes the frame and builds the draw lists, and ImGui_ImplOpenGL3_RenderDrawData issues the OpenGL commands. Draw ImGui last, after your scene, so it sits on top.
The widgets edit variables in place. SliderFloat takes a pointer and a range and writes the new value into fov while the user drags. ColorEdit3 edits three floats, which is why clear is an array. Button returns true on the frame of the click, and the body of the if runs only then.
When you run it, a small window titled "Controls" appears over the dark scene. The first text line reads like the following, and the figures depend on your machine:
Frame time: 16.67 ms (60 FPS)Dragging the color square changes the background immediately, since clear feeds glClearColor in the same frame. Clicking Reset restores the values.
Keep the scene from stealing input
Both ImGui and your scene read the mouse. If the user drags a slider and your camera code also reads the drag, the camera spins while the slider moves. ImGui tells you when it wants the input through two flags in io, which it updates every NewFrame:
if (!io.WantCaptureMouse) {
// the mouse is not over an ImGui window: let the camera use it
update_camera_from_mouse(window);
}
if (!io.WantCaptureKeyboard) {
// no text field has focus: WASD may move the camera
update_camera_from_keys(window);
}WantCaptureMouse is true while the pointer is over an ImGui window or while the user is dragging a widget. WantCaptureKeyboard is true while a text box has keyboard focus. Check them before acting on raw input in your own code, and the interface and scene stop interfering. If your game uses GLFW callbacks and not polling, test the same flags at the top of each callback and return early.
High-DPI displays
On a display with scaling, ImGui draws at framebuffer resolution through the backend, but its font size is in logical pixels, so text can look small. Scale the interface once at startup with the window's content scale:
float xscale, yscale;
glfwGetWindowContentScale(window, &xscale, &yscale);
ImGui::GetStyle().ScaleAllSizes(xscale);
io.FontGlobalScale = xscale;ScaleAllSizes enlarges paddings and widget sizes, and FontGlobalScale enlarges the text. Doing it at startup is enough for a single-monitor program. A program that moves between monitors needs to react to the content scale callback and rebuild the font atlas at the new size.
Common problems
Widgets that draw but do not react almost always mean the backend did not install its callbacks, either because install_callbacks was false or because your own callback replaced it. A crash on the first frame with a message about a missing context means the ImGui call ran before CreateContext. Nothing visible usually means RenderDrawData was called before the scene's glClear, so the clear erased it, or the viewport has zero size. Text boxes that ignore typed characters indicate the character callback was replaced.
The setup follows the example in the ImGui repository, [examples/example_glfw_opengl3](https://github.com/ocornut/imgui/tree/master/examples/example_glfw_opengl3), and the library's own documentation in imgui.cpp.


