Урок №2. Подготовка к первому проекту OpenGL: настройка GLFW, CMake и GLAD
Первое, что нам нужно сделать, прежде чем мы начнем программировать графику — это создать контекст OpenGL и окно приложения для рисования. Однако данные операции являются специфичными для каждой операционной системы, поэтому OpenGL целенаправленно пытается абстрагироваться от них. Это означает, что мы самостоятельно должны создать окно, определить контекст и обрабатывать пользовательский ввод.
К счастью, существует довольно много библиотек, которые обеспечивают необходимый нам функционал, при этом некоторые из них специально нацелены на работу с OpenGL. Эти библиотеки избавят нас от всей специфической работы, связанной с особенностями конкретной операционной системы. Наиболее популярными библиотеками являются: GLUT, SDL, SFML и GLFW. На этих уроках мы будем использовать библиотеку GLFW. Вы также можете использовать и любую другую библиотеку из предоставленного списка, т.к. установка и настройка для большинства из них аналогична установке и настройке GLFW.
Библиотека GLFW
GLFW (англ. «Graphics Library FrameWork») — это библиотека, написанная на языке Си, специально предназначенная для работы с OpenGL. Библиотека GLFW предоставит нам все необходимые инструменты, которые потребуются для рендеринга на экран различных объектов. Благодаря этому мы сможем создавать контексты OpenGL, определять параметры окна и обрабатывать пользовательский ввод, что вполне коррелирует с нашими целями.
Основное внимание на этом и следующем уроках уделяется изучению библиотеки GLFW, созданию корректного контекста OpenGL, а также простого окна, в котором мы и будем рисовать наши объекты. На этом уроке мы пошагово рассмотрим установку библиотеки GLFW, а также процесс сборки и компиляции программы в связке с GLFW.
Примечание: На момент написания данной статьи в качестве среды разработки мы будем использовать Microsoft Visual Studio 2019 (обратите внимание, что наши действия будут аналогичными и с более старыми версиями Visual Studio). Если же вы используете более старую версию Visual Studio (или вообще другую среду разработки), то можете быть спокойны, т.к. процесс установки и настройки GLFW аналогичен в большинстве IDE.
Сборка GLFW
Библиотеку GLFW можно скачать с официального сайта. Стоит отметить, что GLFW уже имеет предварительно скомпилированные бинарные и заголовочные файлы для Visual Studio 2010-2019, но для полноты картины их мы использовать не будем, а вместо этого вручную скомпилируем GLFW из исходного кода. Это делается для того, чтобы вы сами прочувствовали процесс компиляции библиотек с открытым исходным кодом, поскольку не каждая подобная библиотека будет предоставлять возможность скачать предварительно скомпилированные бинарные файлы. Итак, давайте загрузим пакет с исходным кодом.
Примечание: Мы будем собирать все библиотеки в формате 64-битных бинарных файлов, поэтому убедитесь, что скачиваете и используете именно 64-битные бинарные файлы.
После загрузки пакета с файлами исходного кода извлеките и откройте его содержимое. Нас интересуют следующие вещи:
библиотека, которая будет получена в результате компиляции;
Компиляция библиотек из исходного кода гарантирует, что полученная нами библиотека идеально подойдет для нашего процессора и операционной системы, в то время как предварительно скомпилированные бинарные файлы не всегда могут этим похвастаться (иногда они вообще недоступны для вашей системы). Однако проблема проектов, распространяющихся под эгидой открытого программного обеспечения, заключается в том, что не все используют одну и ту же IDE или систему сборки для разработки своего приложения, а это значит, что предоставленные файлы проекта/решения могут быть несовместимы с настройками IDE у других людей. Следовательно, каждый конечный пользователь должен настроить свой собственный проект/решение с учетом полученных *.с / *.cpp и *.h / *.hpp файлов, что почти всегда является довольно трудоемким и громоздким процессом. Но не спешите расстраиваться, для решения данной проблемы уже существует удобный инструмент сборки проектов под названием CMake.
CMake
CMake — это инструмент, который с использованием заранее определенных сценариев может из коллекции файлов исходного кода сгенерировать файлы проектов/решений под выбранную пользователем IDE (например, для Visual Studio, Code::Blocks или Eclipse). Он позволит нам из исходного пакета файлов GLFW создать файл проекта под среду разработки Visual Studio 2019, а затем данный файл мы сможем использовать для компиляции библиотеки. Но сначала нам нужно его скачать, а затем установить.
После установки CMake у вас будет 2 варианта:
запустить CMake из командной строки;
запустить CMake через графический интерфейс.
Поскольку мы не стремимся всё усложнять, то остановимся на варианте с использованием графического интерфейса. Для работы с CMake нам потребуется указать папку с файлами исходного кода проекта (в нашем случае glfw-3.3.2 ) и папку назначения для бинарных файлов. Для папки исходного кода мы собираемся выбрать корневую папку загруженного исходного пакета GLFW, а для папки сборки мы создадим новый каталог build :

После того, как мы прописали пути для исходной и целевой папок, нам нужно нажать кнопку Configure , чтобы CMake смог просмотреть исходные файлы GLFW и выбрать необходимые параметры для сборки.
В следующем окне необходимо задать используемую версию Visual Studio. Т.к. работать мы будем в Visual Studio 2019, то выбираем опцию «Visual Studio 16 2019» :

Далее CMake отобразит возможные варианты сборки библиотеки. Можно оставить значения по умолчанию и снова нажать кнопку Configure , чтобы сохранить настройки:
После установки параметров мы нажимаем кнопку «Generate» , в результате чего в папке build будут созданы необходимые файлы проекта.
Компиляция проекта
Теперь, зайдя в папку build , среди всего прочего можно увидеть файл с именем GLFW.sln , открываем его с помощью Visual Studio 2019:

Поскольку CMake сгенерировал файл проекта, который уже содержит соответствующие параметры конфигурации, нам остается лишь реализовать решение. При этом CMake должен был автоматически настроить вариант компилирования решения в виде 64-битной библиотеки. Благодаря этому мы получим скомпилированный файл библиотеки с именем glfw3.lib , который будет находиться в папке build/src/Debug .
После того, как мы создали библиотеку, нужно убедиться, что IDE знает, где найти данный файл, а также другие подключаемые файлы нашей программы OpenGL. Решить этот вопрос можно двумя способами:
Способ №1: Можно скопировать содержимое папки include проекта GLFW в соответствующую папку include вашей IDE или компилятора, а также скопировать полученный файл glfw3.lib в соответствующую папку /lib вашей IDE или компилятора. Данный способ вполне рабочий, но мы его не рекомендуем, так как новая установка IDE или компилятора приведет к тому, что вам заново придется подключать необходимые файлы.
Способ №2: Вы можете создать новую папку, которая будет содержать все заголовочные файлы и файлы из сторонних библиотек. На эту папку вы впоследствии сможете ссылаться из своей IDE или компилятора. Например, можно создать папку, в которой будут находиться папки Lib и Include . В них мы будем хранить все наши библиотечные и подключаемые файлы, которые собираемся использовать для наших OpenGL-проектов. Получается, что все сторонние библиотеки будут организованы в одном месте (и их можно будет совместно использовать на нескольких компьютерах). Однако, каждый раз при создании нового проекта, мы должны будем указывать IDE соответствующие пути к этим папкам.
Как только необходимые файлы будут сохранены в выбранном вами месте, мы сможем приступить к созданию нашего первого OpenGL-GLFW-проекта.
Наш первый проект
Для начала давайте откроем Visual Studio и создадим новый проект. Для этого нужно выбрать тип проекта «C++» , а далее — «Пустой проект» (не забудьте дать проекту подходящее имя):

Теперь у нас есть рабочее пространство для создания нашего самого первого OpenGL-приложения!
Линкинг проекта
Для того, чтобы наш проект мог использовать GLFW, нам нужно связать с ним полученную библиотеку. Это можно сделать, указав в настройках линкера, что мы хотим использовать библиотеку glfw3.lib , но проект пока не знает где её искать, т.к. все подобные файлы мы переместили в другую папку. Таким образом, сначала мы должны добавить эту папку в наш проект.
Для этого нажмите правой кнопкой мышки на имя проекта в «Обозреватель Решений» > «Свойства» . В появившемся окне выберите «Каталоги VC++» > «Каталоги библиотек» :

Здесь вы можете добавить свои собственные каталоги, чтобы проект знал, где искать необходимые файлы. Это можно сделать, вставив вручную путь до каталога или щелкнув по соответствующей строке и выбрав пункт <Изменить…> , в результате чего откроется следующее окно:

Здесь вы можете добавить столько дополнительных каталогов, сколько захотите, и с этого момента IDE при поиске файлов библиотек также будет просматривать и эти директории. Поэтому, как только вы подключите папку Lib из проекта GLFW, вы сможете использовать все файлы библиотек из этой папки. Аналогично обстоят дела и с добавлением папки Include для заголовочных файлов.
Поскольку для VS были указаны все необходимые файлы, то мы, наконец, можем связать GLFW с нашим проектом, перейдя в раздел «Компоновщик» > «Ввод» :

Чтобы связать библиотеку, нам нужно указать для компоновщика её имя. Так как библиотека называется glfw3.lib , то мы добавляем название этого файла в раздел «Дополнительные зависимости» (вручную или же через пункт <Изменить…> ), и с этого момента при запуске процесса компиляции GLFW будет связан с нашим проектом. В дополнение к GLFW мы также должны добавить ссылки на библиотеку OpenGL, но данные действия будут отличаться, в зависимости от (вашей) используемой операционной системы:
Библиотека OpenGL в Windows. Если вы используете операционную систему Windows, то необходимый нам файл библиотеки OpenGL32.Lib , входящий в пакет Microsoft SDK, уже есть в составе Visual Studio и не требует отдельной установки. Поскольку мы используем компилятор VS и работаем в операционной системе Windows, то всё, что вам нужно сделать — это добавить название файла OpenGL32.Lib к общему списку параметров компоновщика.
Примечание: В примечании подраздела «Сборка GLFW» сказано, что мы собираем все библиотеки в формате 64-битных бинарных файлов. В то же время число «32» в названии файла OpenGL32.Lib может вызвать некоторую путаницу, как бы намекая на то, что в данном случае используется именно 32-битная версия библиотеки. На самом деле это не так. Если у вас установлен пакет Microsoft SDK, то достаточно просто зайти в папку C:\Program Files (x86)\Windows Kits\10\Lib\[Номер_версии_SDK]\um\x64\ и убедиться, что в ней среди прочих файлов находится и наша библиотека:

Больше того, если зайти в папку C:\Program Files (x86)\Windows Kits\10\Lib\[Номер_версии_SDK]\um\x86\, то и там можно встретить файл OpenGL32.Lib:

Другими словами, под одним названием файла OpenGL32.Lib существует две различные версии (32-битная и 64-битная) библиотеки. Поэтому просто не обращайте внимание на то, что в её имени есть часть «32». Всё прекрасно работает и в 64-битном окружении.
Библиотека OpenGL в Linux. Если вы работаете в операционной системе Linux, то вам нужно подключить библиотеку libGL.so с помощью ключей –lGL , добавляемых к параметрам вашего компоновщика. Если вы не можете найти данную библиотеку, то вам, вероятно, необходимо установить любой из пакетов: Mesa, NVidia или AMD dev.
Затем, после добавления библиотек GLFW и OpenGL в настройки компоновщика, вы сможете подключить заголовочные файлы GLFW следующей строкой кода:
Setup OpenGL with Visual Studio 2019
Open Visual Studio , select create a new project , choose Empty Project .
Go to Project -> Properties (Alt + F7) , on the top select All Configurations from Configuration dropdown menu.
Choose Configuration Properties -> C/C++ -> Precompiled Headers , set Precompiled Header ‘s value to Not Using Precompiled Headers .
Choose Configuration Properties -> Linker -> Input , click Additional Dependencies , and then click Edit , and type:
Paste the code I found in Internet to test:
Then Compile and run(x86).
One more thing…
If you upgrade VS, you should re-install OpenGL, since the folder is moved to a higher version one.
C++ — OpenGL — Setting up Visual Studio
The Visual Studio version for this tutorial will be the 2017 (seems to work with the 2015 and 2019 as well).
The glew version will be the 2.2.0.
The freeglut version will be the 3.0.0.
The glew library stands for GL Extension Wrangler.
At the end of this OpenGL tutorial you will be able to display a window with a white square displayed on a black background.
First of all
We are going to use the 32-bit or the 64-bit version.
You have the choice, and it will be specified in the tutorial.
Notice that the version is only based on which platform you want to compile for.
If you plan to create a program to be executed on a 32-bit platform, so use the 32-bit version.
Every platform accept 32-version, so the 64-bit version is only for specific purpose only.
And so the 32-bit version will work on every Windows system.
You’ll need glew headers that could be find on the sourceforge website of the OpenGL Extension Wrangler Library:
freeglut
You’ll also need the freeglut version for Microsoft Visual Studio:
Click the link inside the part freeglut 3.0.0 MSVC Package.
The name of the file you have to download is: freeglut-MSVC-3.0.0-2.mp.zip.
Once you have downloaded it, there is a folder named freeglut inside.
Extract it and rename it to freeglut-3.0.0 in order to have exactly the same name used in this tutorial.
Paths and directories for this setup
The general directory for our setup will be:
- C:\dev
The directory where projects are:
- C:\dev\visual-studio-c++
The directory where libraries are:
- C:\dev\lib
Visual Studio
Open it and create an empty project > File > New > Project > Templates > Visual C++ > Empty Project.
- Name: Shapes2D
- Location: C:\dev\visual-studio-c++\
- Solution: Create a new solution
- Solution name: BadprogTutorial
Your Shapes2D project has been created into your BadprogTutorial solution.
Let’s add a main.cpp > Right click your project > Add > New Item > Visual C++ > C++ File > write the name main.cpp > Add.
Setting all configurations
Right click your Shapes2D project > Properties > On the top left there is a drop down menu > Configuration > Select All Configurations (instead of Debug)
Including header files (includes)
Right click your Shapes2D project > Properties > Configuration Properties > C/C++ > General > Additional Include Directories > Click it.
On the right there is a drop down menu, click <Edit. >.
A new window has appeared: Additional Include Directories.
Click the New Line icon > Click the browse button > Then select the two following folders:
- C:\dev\lib\glew-2.0.0\include
- C:\dev\lib\freeglut-3.0.0\include
Click OK > Apply
Including libraries
Library folders
Right click your Shapes2D project > Properties > Configuration Properties > Linker > General > Additional Library Directories > Click it.
On the right there is a drop down menu, click <Edit. >.
A new window has appeared: Additional Library Directories.
Click the New Line icon > Click the browse button > Then select the two following folders:
For the 64-bit version
- C:\dev\lib\glew-2.0.0\lib\Release\x64
- C:\dev\lib\freeglut-3.0.0\lib\x64
For the 32-bit version
- C:\dev\lib\glew-2.0.0\lib\Release\Win32
- C:\dev\lib\freeglut-3.0.0\lib
Click OK > Apply
Library files
Right click your Shapes2D project > Properties > Configuration Properties > Linker > Input > Additional Dependencies > Click it.
On the right there is a drop down menu, click <Edit. >.
A new window has appeared: Additional Dependencies.
Click the white area and write:
- freeglut.lib (click enter to go the next line)
- glew32.lib
Click OK > Apply > OK.
Your Visual Studio IDE is now ready to play with OpenGL!
Testing the setup
To test the setup, let’s code the most basic code HelloWorld! that you can write with OpenGL.
On the Visual Studio’s top menu there is a dropdown menu with x86 selected.
Click the black tiny triangle on the right of the x86 and select Configuration Manager.
A new window has appeared: Configuration Manager.
On the right select x86 in the dropdown menu and click New.
A new window has appeared: New Solution Platform.
On the right click the the Active solution platform dropdown menu and select:
- Type or select the new platform: x64
- Copy settings from: x86 (or Empty)
You could now close the Configuration Manager and as you can see the platform is now specified as x64.
And you could easily click either x86 or x64 (depending of your libraries version).
freeglut.dll and glew32.dll
Before building it, let’s copy (not move!) the .dll of these two libraries:
For the 64-bit version
- C:\dev\lib\glew-2.0.0\bin\Release\x64\glew32.dll (yes this is the right one)
- and
- C:\dev\lib\freeglut-3.0.0\bin\x64\freeglut.dll
To the following directory:
- C:\dev\visual-studio-c++\BadprogTutorial\x64\Debug
Or if it doesn’t work in: - C:\dev\visual-studio-c++\BadprogTutorial
For the 32-bit version
- C:\dev\lib\glew-2.0.0\bin\Release\Win32\glew32.dll
- and
- C:\dev\lib\freeglut-3.0.0\bin\freeglut.dll
To the following directory:
- C:\dev\visual-studio-c++\BadprogTutorial\Debug
Or if it doesn’t work in: - C:\dev\visual-studio-c++\BadprogTutorial
For both versions (x86 and x64) and to avoid having copy/paste .DLL
If you don’t want to copy/paste your freeglut.dll and glew32.dll from the library directory to your project directory then you have to set their paths directly in your Environment variables.
If you don’t know where to find your Environment variables, open your Windows settings and search for Environment variables.
A system properties window should appear > Advanced tab > Environment variables > In the System variables click New. > Enter, for example for the x64 Freeglut version, the following:
- Variables name: FREEGLUT_LIB
- Variable value: C:\dev\lib\freeglut-3.0.0\bin\x64\
And for the x64 Glew32 version the following:
- Variables name: GLEW32_LIB
- Variable value: C:\dev\lib\glew-2.0.0\bin\Release\x64\
Then click OK > OK.
Do the same for the x86 version except the paths that must, of course, correspond to your x86 versions.
Then close your Visual Studio IDE (yes close it if it still open) in order to get the last Environment variables set.
And you are done, this time you won’t have to copy/paste your .DLL because Windows is now able to find them automatically.
Open Visual Studio again to build and compile your first OpenGL application.
Building the project
On the Visual Studio’s top menu, select either x86 or x64 and build the project.
If there is no error, right click the Shapes2D project > Debug > Start new instance.
If all is OK, you should see a black window with a white square.
Possible Errors
If you had some errors like these ones, it’s because you try to play with a different version from the one specified in the setup configuration.
For example if you have set up the configuration with the 64-bit version, you have to build it with the x64 configuration.
Same thing for the 32-bit version, set up with the 32-bit library version and build it as a x86 configuration.
So double check the paths you’ve just entered in the setup configuration.
Here the errors:
Conclusion
Now that your Visual Studio has been set up, you could start creating OpenGL applications.
Getting-started/Creating-a-window
The first thing we need to do before we start creating stunning graphics is to create an OpenGL context and an application window to draw in. However, those operations are specific per operating system and OpenGL purposefully tries to abstract itself from these operations. This means we have to create a window, define a context, and handle user input all by ourselves.
Luckily, there are quite a few libraries out there that provide the functionality we seek, some specifically aimed at OpenGL. Those libraries save us all the operation-system specific work and give us a window and an OpenGL context to render in. Some of the more popular libraries are GLUT, SDL, SFML and GLFW. On LearnOpenGL we will be using GLFW. Feel free to use any of the other libraries, the setup for most is similar to GLFW’s setup.
GLFW is a library, written in C, specifically targeted at OpenGL. GLFW gives us the bare necessities required for rendering goodies to the screen. It allows us to create an OpenGL context, define window parameters, and handle user input, which is plenty enough for our purposes.
The focus of this and the next chapter is to get GLFW up and running, making sure it properly creates an OpenGL context and that it displays a simple window for us to mess around in. This chapter takes a step-by-step approach in retrieving, building and linking the GLFW library. We’ll use Microsoft Visual Studio 2019 IDE as of this writing (note that the process is the same on the more recent visual studio versions). If you’re not using Visual Studio (or an older version) don’t worry, the process will be similar on most other IDEs.
Building GLFW
GLFW can be obtained from their webpage’s download page. GLFW already has pre-compiled binaries and header files for Visual Studio 2012 up to 2019, but for completeness’ sake we will compile GLFW ourselves from the source code. This is to give you a feel for the process of compiling open-source libraries yourself as not every library will have pre-compiled binaries available. So let’s download the Source package.
We’ll be building all libraries as 64-bit binaries so make sure to get the 64-bit binaries if you’re using their pre-compiled binaries.
Once you’ve downloaded the source package, extract it and open its content. We are only interested in a few items:
- The resulting library from compilation.
- The include folder.
Compiling the library from the source code guarantees that the resulting library is perfectly tailored for your CPU/OS, a luxury pre-compiled binaries don’t always provide (sometimes, pre-compiled binaries are not available for your system). The problem with providing source code to the open world however is that not everyone uses the same IDE or build system for developing their application, which means the project/solution files provided may not be compatible with other people’s setup. So people then have to setup their own project/solution with the given .c/.cpp and .h/.hpp files, which is cumbersome. Exactly for those reasons there is a tool called CMake.
CMake
CMake is a tool that can generate project/solution files of the user’s choice (e.g. Visual Studio, Code::Blocks, Eclipse) from a collection of source code files using pre-defined CMake scripts. This allows us to generate a Visual Studio 2019 project file from GLFW’s source package which we can use to compile the library. First we need to download and install CMake which can be downloaded on their download page.
Once CMake is installed you can choose to run CMake from the command line or through their GUI. Since we’re not trying to overcomplicate things we’re going to use the GUI. CMake requires a source code folder and a destination folder for the binaries. For the source code folder we’re going to choose the root folder of the downloaded GLFW source package and for the build folder we’re creating a new directory build and then select that directory.

Once the source and destination folders have been set, click the Configure button so CMake can read the required settings and the source code. We then have to choose the generator for the project and since we’re using Visual Studio 2019 we will choose the Visual Studio 16 option (Visual Studio 2019 is also known as Visual Studio 16). CMake will then display the possible build options to configure the resulting library. We can leave them to their default values and click Configure again to store the settings. Once the settings have been set, we click Generate and the resulting project files will be generated in your build folder.
Compilation
In the build folder a file named GLFW.sln can now be found and we open it with Visual Studio 2019. Since CMake generated a project file that already contains the proper configuration settings we only have to build the solution. CMake should’ve automatically configured the solution so it compiles to a 64-bit library; now hit build solution. This will give us a compiled library file that can be found in build/src/Debug named glfw3.lib .
- We find the /lib and /include folders of the IDE/compiler and add the content of GLFW’s include folder to the IDE’s /include folder and similarly add glfw3.lib to the IDE’s /lib folder. This works, but it’s is not the recommended approach. It’s hard to keep track of your library and include files and a new installation of your IDE/compiler results in you having to do this process all over again.
- Another approach (and recommended) is to create a new set of directories at a location of your choice that contains all the header files/libraries from third party libraries to which you can refer to from your IDE/compiler. You could, for instance, create a single folder that contains a Libs and Include folder where we store all our library and header files respectively for OpenGL projects. Now all the third party libraries are organized within a single location (that can be shared across multiple computers). The requirement is, however, that each time we create a new project we have to tell the IDE where to find those directories.
Our first project
First, let’s open up Visual Studio and create a new project. Choose C++ if multiple options are given and take the Empty Project (don’t forget to give your project a suitable name). Since we’re going to be doing everything in 64-bit and the project defaults to 32-bit, we’ll need to change the dropdown at the top next to Debug from x86 to x64:

Once that’s done, we now have a workspace to create our very first OpenGL application!
Linking
In order for the project to use GLFW we need to link the library with our project. This can be done by specifying we want to use glfw3.lib in the linker settings, but our project does not yet know where to find glfw3.lib since we store our third party libraries in a different directory. We thus need to add this directory to the project first.
We can tell the IDE to take this directory into account when it needs to look for library and include files. Right-click the project name in the solution explorer and then go to VC++ Directories as seen in the image below:

From there on out you can add your own directories to let the project know where to search. This can be done by manually inserting it into the text or clicking the appropriate location string and selecting the <Edit..> option. Do this for both the Library Directories and Include Directories :

Here you can add as many extra directories as you’d like and from that point on the IDE will also search those directorie when searching for library and header files. As soon as your Include folder from GLFW is included, you will be able to find all the header files for GLFW by including <GLFW/..> . The same applies for the library directories.
Since VS can now find all the required files we can finally link GLFW to the project by going to the Linker tab and Input :

To then link to a library you’d have to specify the name of the library to the linker. Since the library name is glfw3.lib , we add that to the Additional Dependencies field (either manually or using the <Edit..> option) and from that point on GLFW will be linked when we compile. In addition to GLFW we should also add a link entry to the OpenGL library, but this may differ per operating system:
OpenGL library on Windows
If you’re on Windows the OpenGL library opengl32.lib comes with the Microsoft SDK, which is installed by default when you install Visual Studio. Since this chapter uses the VS compiler and is on windows we add opengl32.lib to the linker settings. Note that the 64-bit equivalent of the OpenGL library is called opengl32.lib , just like the 32-bit equivalent, which is a bit of an unfortunate name.
OpenGL library on Linux
On Linux systems you need to link to the libGL.so library by adding -lGL to your linker settings. If you can’t find the library you probably need to install any of the Mesa, NVidia or AMD dev packages.
Then, once you’ve added both the GLFW and OpenGL library to the linker settings you can include the header files for GLFW as follows:
For Linux users compiling with GCC, the following command line options may help you compile the project: -lglfw3 -lGL -lX11 -lpthread -lXrandr -lXi -ldl . Not correctly linking the corresponding libraries will generate many undefined reference errors.
This concludes the setup and configuration of GLFW.
We’re still not quite there yet, since there is one other thing we still need to do. Because OpenGL is only really a standard/specification it is up to the driver manufacturer to implement the specification to a driver that the specific graphics card supports. Since there are many different versions of OpenGL drivers, the location of most of its functions is not known at compile-time and needs to be queried at run-time. It is then the task of the developer to retrieve the location of the functions he/she needs and store them in function pointers for later use. Retrieving those locations is OS-specific. In Windows it looks something like this:
As you can see the code looks complex and it’s a cumbersome process to do this for each function you may need that is not yet declared. Thankfully, there are libraries for this purpose as well where GLAD is a popular and up-to-date library.
Setting up GLAD
GLAD is an open source library that manages all that cumbersome work we talked about. GLAD has a slightly different configuration setup than most common open source libraries. GLAD uses a web service where we can tell GLAD for which version of OpenGL we’d like to define and load all relevant OpenGL functions according to that version.
Go to the GLAD web service, make sure the language is set to C++, and in the API section select an OpenGL version of at least 3.3 (which is what we’ll be using; higher versions are fine as well). Also make sure the profile is set to Core and that the Generate a loader option is ticked. Ignore the extensions (for now) and click Generate to produce the resulting library files.
GLAD by now should have provided you a zip file containing two include folders, and a single glad.c file. Copy both include folders ( glad and KHR ) into your include(s) directoy (or add an extra item pointing to these folders), and add the glad.c file to your project.
After the previous steps, you should be able to add the following include directive above your file:
Hitting the compile button shouldn’t give you any errors, at which point we’re set to go for the next chapter where we’ll discuss how we can actually use GLFW and GLAD to configure an OpenGL context and spawn a window. Be sure to check that all your include and library directories are correct and that the library names in the linker settings match the corresponding libraries.