Installing GLAD OpenGL Loader Library Установка библиотеки-загрузчика OpenGL GLAD

A step-by-step guide to generating, extracting, and configuring the GLAD OpenGL loader library for OpenGL 3.3 Core on Windows and Ubuntu. Пошаговое руководство по генерации, распаковке и настройке библиотеки-загрузчика GLAD для OpenGL 3.3 Core в Windows и Ubuntu.

If you haven't set up C/C++ development tools on your system, follow the relevant guide: Если вы еще не настроили инструменты разработки C/C++ на вашей системе, следуйте соответствующей инструкции:

Step 1: Generate & Download Source Code Шаг 1: Генерация и скачивание исходного кода

GLAD requires generating custom C loader files for your specific OpenGL version and profile using the web generator: GLAD требует генерации пользовательских C-файлов загрузчика под вашу конкретную версию и профиль OpenGL с помощью веб-генератора:

  1. Go to the GLAD Web Generator and select the following settings: Перейдите в веб-генератор GLAD и выберите следующие настройки:
    • Language: C/C++
    • Specification: OpenGL
    • API gl: Version 3.3
    • Profile: Core
    • Options: Generate a loader (check this box)
  2. Click Generate at the bottom of the page. Нажмите Generate в нижней части страницы.
  3. Download the glad.zip archive. (Note: the GLAD generator version, e.g. 0.1.36, can be seen at the bottom footer of the generator page). Скачайте архив glad.zip. (Примечание: версию генератора GLAD, например 0.1.36, можно найти в футере страницы генератора).

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

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

Unzip the downloaded glad.zip archive into C:\libs\glad-0.1.36\opengl-3.3. Распакуйте скачанный архив glad.zip в папку C:\libs\glad-0.1.36\opengl-3.3.

Option B: Ubuntu (WSL) Вариант B: Ubuntu (WSL)

Create the target directory and extract glad.zip directly from your Windows Downloads folder: Создайте целевую директорию и распакуйте glad.zip прямо из папки Загрузок Windows:

mkdir -p ~/libs/glad-0.1.36/opengl-3.3
unzip -o /mnt/c/Users/$USER/Downloads/glad.zip -d ~/libs/glad-0.1.36/opengl-3.3

Expected Directory Structure Ожидаемая структура директории

Ensure that the extracted directory has the following folder hierarchy: Убедитесь, что распакованная директория имеет следующую иерархию папок:

glad-0.1.36/opengl-3.3/
├── include/
│   ├── glad/glad.h
│   └── KHR/khrplatform.h
└── src/
    └── glad.c

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

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

Windows (Command Prompt / PowerShell)

mkdir C:\projects\glad-test
cd C:\projects\glad-test

Ubuntu (Terminal)

mkdir -p ~/projects/glad-test
cd ~/projects/glad-test

Step 4: Create Source Files (main.c & CMakeLists.txt) Шаг 4: Создание исходных файлов (main.c и 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.c
notepad CMakeLists.txt

Ubuntu (Terminal / Nano)

nano main.c
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.c 1. Содержимое файла main.c

#include <stdio.h>
#include <glad/glad.h>

int main(int argc, char *argv[]) {
    printf("GLAD header included successfully!\n");
    /* Note: Calling OpenGL functions requires an active context and calling gladLoadGL() or gladLoadGLLoader() */
    return 0;
}

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

cmake_minimum_required(VERSION 3.21)
project(glad_test C)

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

add_executable(app main.c ${GLAD_DIR}/src/glad.c)

target_include_directories(app PRIVATE ${GLAD_DIR}/include)

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

Windows (MinGW / Batch Scripts)

config-exe.bat

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

build-exe.bat

cmake --build dist/win

run-exe.bat

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

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

config-exe.bat
build-exe.bat
run-exe.bat

Ubuntu (Bash Scripts)

config-bin.sh

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

build-bin.sh

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

run-bin.sh

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

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

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

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