Installing Dear ImGui Library on Windows & Ubuntu (OpenGL 3.3) Установка библиотеки Dear ImGui под Windows и Ubuntu (OpenGL 3.3)

A step-by-step guide to downloading, extracting, and configuring the latest release of Dear ImGui with OpenGL 3.3 and GLAD in your CMake projects on Windows and Ubuntu. Пошаговое руководство по скачиванию, распаковке и настройке последней версии библиотеки Dear ImGui с OpenGL 3.3 и GLAD в проектах CMake под Windows и Ubuntu.

Before proceeding, make sure you have set up C/C++ development tools and the GLAD OpenGL loader library on your system using the appropriate guides: Перед продолжением убедитесь, что вы настроили инструменты разработки C/C++ и библиотеку-загрузчик OpenGL GLAD в вашей системе, следуя соответствующим инструкциям:

Step 1: Download Source Code Шаг 1: Скачивание исходного кода

Check and download the latest release (such as v1.93.0) directly from the official Dear ImGui repository on GitHub: Проверьте и скачайте последнюю версию (например, v1.93.0) напрямую со страницы релизов Dear ImGui на GitHub:

Open Dear ImGui Releases (GitHub) Открыть релизы Dear ImGui (GitHub) Download Dear ImGui 1.93.0 (.zip) Скачать Dear ImGui 1.93.0 (.zip)

For Ubuntu, you can download the release directly via wget in the terminal: В Ubuntu вы можете скачать релиз напрямую с помощью wget в терминале:

sudo apt update && sudo apt install -y wget unzip git

cd ~
wget https://github.com/ocornut/imgui/archive/refs/tags/v1.93.0.zip -O imgui-1.93.0.zip

Step 2: Extract the Library Шаг 2: Распаковка библиотеки

Option A: Windows Вариант A: Windows

Unzip the downloaded archive so that the source files are located in C:\libs\imgui-1.93.0. Распакуйте скачанный архив так, чтобы исходные файлы находились в папке C:\libs\imgui-1.93.0.

Option B: Ubuntu Вариант B: Ubuntu

Unzip the archive into the ~/libs directory: Распакуйте архив в директорию ~/libs:

mkdir -p ~/libs
unzip -o imgui-1.93.0.zip -d ~/libs/
rm -f imgui-1.93.0.zip

This will place the library files into ~/libs/imgui-1.93.0. Исходные файлы библиотеки будут распакованы по пути ~/libs/imgui-1.93.0.

Step 3: Create Project Directory Шаг 3: Создание директории проекта

Create a workspace folder and a new directory for your ImGui OpenGL test project: Создайте рабочую папку для проектов и новую директорию для вашего тестового проекта ImGui OpenGL:

Windows (Command Prompt / PowerShell)

mkdir C:\projects\imgui-opengl-test
cd C:\projects\imgui-opengl-test

Ubuntu (Terminal)

mkdir -p ~/projects/imgui-opengl-test
cd ~/projects/imgui-opengl-test

Step 4: Create Source Files (main.cpp & CMakeLists.txt) Шаг 4: Создание исходных файлов (main.cpp и CMakeLists.txt)

You can create these files using Notepad / Sublime Text on Windows, or nano in Ubuntu terminal: Вы можете создать эти файлы через Блокнот / Sublime Text в Windows или с помощью nano в терминале Ubuntu:

Windows (Terminal / Notepad)

notepad main.cpp
notepad CMakeLists.txt

Ubuntu (Terminal / Nano)

nano main.cpp
nano CMakeLists.txt
Quick Nano Commands (Ubuntu):Быстрые команды Nano (Ubuntu): Paste code with Right Mouse Button (RMB) → Press Ctrl + O and Enter to save → Press Ctrl + X to exit. Вставьте код правой кнопкой мыши (ПКМ) → Нажмите Ctrl + O и Enter для сохранения → Нажмите Ctrl + X для выхода.

1. File Contents for main.cpp 1. Содержимое файла main.cpp

#include <iostream>
#include <glad/glad.h>
#include "imgui.h"
#include "imgui_impl_opengl3.h"

int main(int argc, char** argv) {
    // Initialize ImGui context
    IMGUI_CHECKVERSION();
    ImGui::CreateContext();
    ImGuiIO& io = ImGui::GetIO(); (void)io;
    io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard;

    // Set display size and frame delta time for headless execution verification
    io.DisplaySize = ImVec2(1280.0f, 720.0f);
    io.DeltaTime = 1.0f / 60.0f;

    // Build font atlas explicitly when renderer backend isn't creating textures
    unsigned char* pixels;
    int width, height;
    io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);

    ImGui::StyleColorsDark();

    std::cout << "Dear ImGui version: " << IMGUI_VERSION << std::endl;
    std::cout << "ImGui OpenGL 3.3 Backend configured successfully!" << std::endl;

    // Simulate ImGui frame lifecycle
    ImGui::NewFrame();
    ImGui::Begin("OpenGL 3.3 Test Window");
    ImGui::Text("Hello, OpenGL 3.3 with Dear ImGui!");
    ImGui::End();
    ImGui::Render();

    // Cleanup ImGui context
    ImGui::DestroyContext();

    return 0;
}

2. File Contents for CMakeLists.txt 2. Содержимое файла CMakeLists.txt

cmake_minimum_required(VERSION 3.21)

if(NOT CMAKE_BUILD_TYPE)
    set(CMAKE_BUILD_TYPE "Debug")
endif()

project(imgui_opengl_test CXX C)

set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)

# -----------------------------------------------------------------------------
# Paths
# -----------------------------------------------------------------------------
if(WIN32)
    set(IMGUI_DIR "C:/libs/imgui-1.93.0")
    set(GLAD_DIR  "C:/libs/glad-0.1.36/opengl-3.3")
else()
    set(IMGUI_DIR "$ENV{HOME}/libs/imgui-1.93.0")
    set(GLAD_DIR  "$ENV{HOME}/libs/glad-0.1.36/opengl-3.3")
endif()

# -----------------------------------------------------------------------------
# ImGui Sources (including OpenGL3 Backend)
# -----------------------------------------------------------------------------
set(IMGUI_SOURCES
    ${IMGUI_DIR}/imgui.cpp
    ${IMGUI_DIR}/imgui_demo.cpp
    ${IMGUI_DIR}/imgui_draw.cpp
    ${IMGUI_DIR}/imgui_tables.cpp
    ${IMGUI_DIR}/imgui_widgets.cpp
    ${IMGUI_DIR}/backends/imgui_impl_opengl3.cpp
)

# -----------------------------------------------------------------------------
# Executable Target
# -----------------------------------------------------------------------------
add_executable(app
    main.cpp
    ${IMGUI_SOURCES}
    ${GLAD_DIR}/src/glad.c
)

# -----------------------------------------------------------------------------
# Include Directories
# -----------------------------------------------------------------------------
target_include_directories(app PRIVATE
    ${IMGUI_DIR}
    ${IMGUI_DIR}/backends
    ${GLAD_DIR}/include
)

# -----------------------------------------------------------------------------
# Backend Selection Definition
# -----------------------------------------------------------------------------
target_compile_definitions(app PRIVATE
    IMGUI_IMPL_OPENGL_LOADER_GLAD
)

# -----------------------------------------------------------------------------
# Static C++ Runtime (Applied to BOTH Windows & Ubuntu)
# -----------------------------------------------------------------------------
target_link_options(app PRIVATE -static-libgcc -static-libstdc++)

# -----------------------------------------------------------------------------
# Optimization & Symbol Stripping (Release Builds Only)
# -----------------------------------------------------------------------------
if(CMAKE_BUILD_TYPE STREQUAL "Release" OR CMAKE_BUILD_TYPE STREQUAL "MinSizeRel")
    target_compile_options(app PRIVATE -Os)
    target_link_options(app PRIVATE -s)
endif()

# -----------------------------------------------------------------------------
# Platform Linking & Dependencies
# -----------------------------------------------------------------------------
if(WIN32)
    target_link_libraries(app PRIVATE
        opengl32
    )

    # Windows static linking & subsystem selection
    target_link_options(app PRIVATE -static)

    if(CMAKE_BUILD_TYPE STREQUAL "Debug")
        target_link_options(app PRIVATE -mconsole)
    else()
        target_link_options(app PRIVATE -mwindows)
    endif()
else()
    target_link_libraries(app PRIVATE
        GL
        dl
        pthread
        m
    )
endif()

Step 5: Create Build & Execution Scripts Шаг 5: Создание скриптов сборки и запуска

Windows (MinGW / Batch Scripts)

config-win.bat

cmake -G Ninja -S . -B dist/win

build-win.bat

cmake --build dist/win

run-win.bat

@echo off
.\dist\win\app.exe

Run the scripts sequentially in Command Prompt or PowerShell: Последовательно запустите скрипты в командной строке или PowerShell:

config-win.bat
build-win.bat
run-win.bat

Ubuntu (Bash Scripts)

config-linux.sh

#!/usr/bin/env bash
set -e
cmake -G Ninja -S . -B dist/linux

build-linux.sh

#!/usr/bin/env bash
set -e
cmake --build dist/linux

run-linux.sh

#!/usr/bin/env bash
set -e
./dist/linux/app

Grant execute permissions on Ubuntu before running: Предоставьте права на выполнение в Ubuntu перед запуском:

chmod +x config-linux.sh build-linux.sh run-linux.sh
./config-linux.sh
./build-linux.sh
./run-linux.sh

Step 6: Expected Output Шаг 6: Ожидаемый результат

After running the build and execution scripts, the application will initialize Dear ImGui with the OpenGL 3.3 backend and output the following lines to your terminal: После запуска скриптов сборки и выполнения приложение инициализирует Dear ImGui с бэкендом OpenGL 3.3 и выведет следующие строки в терминал:

Dear ImGui version: 1.93.0
ImGui OpenGL 3.3 Backend configured successfully!

Step 7: Next Steps Шаг 7: Следующие шаги

Now that you have configured Dear ImGui with the OpenGL 3.3 backend, you can integrate it with SDL3: Теперь, когда вы настроили Dear ImGui с бэкендом OpenGL 3.3, вы можете перейти к интеграции с SDL3:

Integrating Dear ImGui with SDL3 on Windows & Ubuntu (OpenGL 3.3) Интеграция Dear ImGui с SDL3 под Windows и Ubuntu (OpenGL 3.3)


Support My Work Поддержать проект

If these tutorials helped you, consider buying me a coffee! Если эти туториалы вам помогли, вы можете поддержать автора.

Sberbank (Russia only) Сбербанк (только для РФ)

Sberbank SBP QR Code

Direct transfer via phone number (Russia only) Перевод по номеру телефона (только для РФ)

+7 (917) 212-29-59

USDT TRC20

USDT TRC20 QR Code

Support via Cryptocurrency Поддержка криптовалютой

TMtY1YifNf6FKvgeFmqKGQR4NStKr3csGp