Opengl Configuring GLFW and Glew

Download as pdf or txt
Download as pdf or txt
You are on page 1of 18

OpenGL: Configuring GLFW and GLEW in Visual C++ Express

Posted by DimasTheDriver | Aug 14th, 2013 | Filed under Featured, Programming

This post shows how to configure Visual C++ Express 2010 with GLFW (version 3.0.1) and
GLEW (version 1.9.0)[1].
There are many tutorials on the internet that explains how to configureVisual
C++ Express with those exact same libraries[2]. However, this one focus on how to proceed
with this setup while avoiding copying any of the header and library files to
the Visual C++ Express installation folders, system folders or the Windows SDK folder.
To put it into a summarized manner, all you have to do is to download and install the Visual
C++ Express; download and extract the GLFW and GLEW binaries; create a project; configure
the project so it can locate the GLFW and GLEW header and lib files; and initialize and use
both libraries in your application.
Therefore, this tutorial is divided into 8 parts:
1. Download the required files
2. Install and extract
3. Create a project and a solution
4. Configuring the project
5. Building the project
6. Troubleshooting
7. Additional Notes
8. References

1. Download the required files


The first thing that has to be done is to download GLFW, GLEW
and Visual C++ Express 2010 from the following URLs:
GLFW: http://www.glfw.org/download.html (File: glfw-3.0.1.bin.WIN32.zip, regardless
whether using Windows 64 bits or not)[3].
GLEW: http://sourceforge.net/projects/glew/files/glew/1.9.0/ (File: gle w-1.9.0-
win32.zip, regardless whether using Windows 64 bits or not)[4].
Visual C++ Express 2010: https://www.microsoft.com/visualstudio/eng/downloads#d-
2010-express (This application needs to be registered after 30 days. It’s free).
2. Install and extract
Now, install Visual C++ Express 2010. During installation, you will be prompted to
installMicrosoft SQL Server 2008 Express. This isn’t necessary for building OpenGL
applications, so installing it is optional, in this case. Just make sure that the .NET Framework
(version 4.x)[5] gets installed along with Visual C++ Express 2010.
If your user has access to the root of the system drive (normally C:\), just create a folder there
and name it opengl-wrappers or whatever other name you want to. Just keep the name short
and avoid using characters such as spaces and capital letters.
If you don’t have access to the root of the system drive, just create the opengl-
wrappe rs folderelsewhere. Just make sure that it’s created at the shortest possible path.
This folder will hold both GLEW and GLFW files, so place both glfw-
3.0.1.bin.WIN32.zip and gle w-1.9.0-win32.zip files there and extract them:

Notice that I’ve stripped the version identifier from both glfw and glew folders. This isn’t
necessary. I did that to simplify the folder paths to be referenced later on the Visual Express
project configuration (explained in detail at part 4).
Now, launch Visual C++ Express 2010.
3. Create a project and a solution
If you are opening Visual C++ Express 2010 for the first time, you may have to wait for it to
complete its initial configuration. After that, close any open solution that might be open
(File →Close Solution), since we are going to create one from scratch.
To create a project and a solution, just select File → New → Project. This will open the New
Projectdialog. There, fill in the project Name and the Solution Name fields. Also, select
the Win32 Console Application as the project template[6]. Make sure that the checkbox Create
directory for solution is selected:

Select File → New → Project.


Then, give the project and the solution a name. For this tutorial, the project will be named
‘Test’ and the solution, ‘OpenGLtest’. Leave the option Create directory for solutionchecked.
Another dialog will appear. This one is the Win32 Application Wizard dialog, where further
configurations to the project can be set. Just click on Next:

Simply press the Next button.


At the next dialog, select Console Application as the Application Type.
Also, deselect thePrecompiled header checkbox and tick the Empty Project checkbox. So, it
will look like this:
Choose Console Application as the ‘Application Type’. At ‘Application Options’ Deselect
the Precompiled Header box and mark the Empty Project option.
Press the Finish button.
4. Configuring the project
This part shows how to configure the project so that Visual C++ Express 2010 can find the
GLFW and GLEW headers and libraries to link with when building the ‘Test.exe’ application.
However, before opening the project’s configuration, at least a single .cpp file must be added to
the project, so that the C++ options inside the project’s Properties can be edited. This is done
by right clicking the Source Files folder and selecting Add → New Item. Like this:
Right-click the Source Files folder and select Add → New Item
A dialog will pop-up. There, select the C++ File (.cpp) as the file type and type main at
the Namefield:

Name it main. Select .cpp as the file extension.


Click on the Add button to confirm. Just leave the main.cpp file empty, for now.
Finally, right-click on the ‘Test’ project and select Properties:
Right-click the project and select Properties.
This will open the project’s properties, which is where the paths to the headers and library files
for both GLEW and GLFW are configured. At the Configuration drop-down menu, select All
Configurations. Also, make sure that the selected Platform is set to Win32.

Select All Configurations and Win32 on the drop down selectors located at the top of the
dialog.
After that, select C/C++ → General. Click on the Additional Include Directories drop-down
menu and select <Edit…>:
Select C/C++ → General → Additional Include Directories. Then click on <Edit…>.
A dialog will open, where you can add directories that contains the GLEW and GLFW headers.
The following directories have to be added:
C:\opengl-wrappers\glew\include
C:\opengl-wrappers\glfw\include
The Additional Include Directories should look like this:

Click on the yellow folder icon and then on the button with the ellipsis to browse to the desired
directory instead of manually typing the folder path.
To confirm, just press the OK button.
Now that Visual C++ Express 2010 can find the GLFW and GLEW headers, it needs to find
their corresponding library files. In order to do so, select Linker → General → Additional
Library Directories. Again, select the drop-down menu and click on <Edit…>:

Select Linker → General → Additional Library Directories. Then click on <Edit…>.


A dialog just about the same as the previous one will be presented. Add the following
directories:
C:\opengl-wrappers\glew\lib[7]
C:\opengl-wrappers\glfw\lib- msvc100 (or lib- mscv110 if you are using Visual Studio
Express 2011).
The Additional Library Directories will look like this:
Click on the yellow folder icon and then on the button with the ellipsis to browse to the desired
directory instead of manually typing the folder path.
Again, click on the OK button.
Next, navigate to Linker → Input → Additional Dependencies. One last time, click on the drop-
down menu to the far right and select <Edit…>:

Select Linker → Input → Additional Dependencies. Then click on <Edit…>.


A dialog with a text field will open. There, add the following library files, one per line:
opengl32.lib
glu32.lib
glew32.lib
glfw3.lib
After adding the libraries, the Additional Dependencies dialog will look like this:
Add the following libraries: opengl32.lib, glu32.lib, glew32.lib andglfw3.lib.
Click on the OK button to confirm and dismiss the Additional Dependencies dialog. Finally,
hitApply and them OK to dismiss the Project Property Pages dialog:

Select Apply and then OK to confirm and dismiss the project’s Property Pages dialog.
One last thing: copy the glew32.dll file located at opengl-wrappe rs/glew/bin to
the Test project folder[8]:
Screenshot showing the glew32.dll file copied to the ‘Test’ project folder.
All Visual C++ Express 2010 configurations are now completed! Let’s try to build the project.
5. Building the project
At this point, we have to somehow verify whether the project configurations were successful
and if the libraries are being correctly referenced and linked. Therefore, copy and paste the
following code into the main.cpp file:
view plaincopy to clipboardprint?

1. //Include GLEW
2. #include <GL/glew.h>
3.
4. //Include GLFW
5. #include <GLFW/glfw3.h>
6.
7. //Include the standard C++ headers
8. #include <stdio.h>
9. #include <stdlib.h>
10.
11. //Define an error callback
12. static void error_callback(int error, const char* description)
13. {
14. fputs(description, stderr);
15. _fgetchar();
16. }
17.
18. //Define the key input callback
19. static void key_callback(GLFWwindow* window, int key, int scancode, int action, int
mods)
20. {
21. if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)
22. glfwSetWindowShouldClose(window, GL_TRUE);
23. }
24.
25. int main( void )
26. {
27. //Set the error callback
28. glfwSetErrorCallback(error_callback);
29.
30. //Initialize GLFW
31. if (!glfwInit())
32. {
33. exit(EXIT_FAILURE);
34. }
35.
36. //Set the GLFW window creation hints - these are optional
37. //glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); //Request a specific
OpenGL version
38. //glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); //Request a specific
OpenGL version
39. //glfwWindowHint(GLFW_SAMPLES, 4); //Request 4x antialiasing
40. //glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFI
LE);
41.
42. //Declare a window object
43. GLFWwindow* window;
44.
45. //Create a window and create its OpenGL context
46. window = glfwCreateWindow(640, 480, "Test Window", NULL, NULL);
47.
48. //If the window couldn't be created
49. if (!window)
50. {
51. fprintf( stderr, "Failed to open GLFW window.\n" );
52. glfwTerminate();
53. exit(EXIT_FAILURE);
54. }
55.
56. //This function makes the context of the specified window current on the calling threa
d.
57. glfwMakeContextCurrent(window);
58.
59. //Sets the key callback
60. glfwSetKeyCallback(window, key_callback);
61.
62. //Initialize GLEW
63. GLenum err = glewInit();
64.
65. //If GLEW hasn't initialized
66. if (err != GLEW_OK)
67. {
68. fprintf(stderr, "Error: %s\n", glewGetErrorString(err));
69. return -1;
70. }
71.
72. //Set a background color
73. glClearColor(0.0f, 0.0f, 1.0f, 0.0f);
74.
75. //Main Loop
76. do
77. {
78. //Clear color buffer
79. glClear(GL_COLOR_BUFFER_BIT);
80.
81. //Swap buffers
82. glfwSwapBuffers(window);
83. //Get and organize events, like keyboard and mouse input, window resizing, etc...
84. glfwPollEvents();
85.
86. } //Check if the ESC key had been pressed or if the window had been closed
87. while (!glfwWindowShouldClose(window));
88.
89. //Close OpenGL window and terminate GLFW
90. glfwDestroyWindow(window);
91. //Finalize and clean up GLFW
92. glfwTerminate();
93.
94. exit(EXIT_SUCCESS);
95. }

After copying the code and waiting for a few seconds, if the include or the GLFW and GLEW
function calls have a red underline beneath them, there’s a problem with the project
configuration. Return to the fourth part of the tutorial. Case everything looks fine, continue
reading this section.
Right at the start of the above code, some headers are being included. The include order
matters! To use GLEW with GLFW, the GLEW header must be included before the GLFW
header. Then, after that, include any other library that may be required (lines 1 through 10).
Moving on, two static functions that are later set as GLFW callbacks are defined: the error and
keyboard callbacks. They are just like the ones found at the official GLFW documentation
(lines 12 through 23). The first one prints any initialization errors to the console and the second
one makes the application close if the escape key is pressed.
Finally, the main() function is being defined. The first line of code inside it assigns the error
callback (line 28), again just as stated on GLFW’s official documentation.
Lines 31 through 34 simply initialize GLFW. If a problem takes place, the application exits.
The next set of lines are purely optional, however it’s highly likely that you are going to be
using them (lines 36 through 40). They set some request for specific features to the GLFW
window. The first and second ones, if uncommented, will request a window to be created with
a OpenGL context greater than 3.0 (3.1, 3.2 or 3.3, depending on the hardware)[9] (lines 37 and
38).
The last of this set of lines, if uncommented, simply request the correct OpenGL profile (line
40). Some problems might arise if setting this incorrectly. Read the Troubleshooting section of
this tutorial.
After all those verifications, it’s safe to try to create a window. This is done by declaring
aGLFWwindow object at line 43 and at the following line, where a 640 by 480 pixels window
with the title “Test Window” is created (line 46)[10].
With some luck, a GLFW window gets created. So, the next if statement on the code checks
whether everything went as expected. In case something goes wrong while creating the
window, GLFW terminates and closes the application (lines 49 through 53).
Afterwards, the window is associated with the current OpenGL context (line 57). Please make
sure that the glwfMakeContextCurrent() method call is made before initializing GLEW.
Another GLFW function call assigns the key callback to be used (line 60).
With that, GLEW is initialized and the following if statement just checks whether it was
successful, closing the application if it wasn’t. This part of the code has been extracted from
GLEW’s documentation (line 63 through 70).
A blue color is set as the background’s clear color. Although it has nothing to do with GLFW
or GLEW initialization, it’s an easy way to tell if everything has initialized correctly, including
the association of the correct OpenGL context with the GLFW window (line 73).
At the end of the main function declaration, a do-while loop is set to run indefinitely until the
GLFW needs to close due to an error, or if the window is closed by the user (line 87).
Inside the loop, the color buffer is cleared, the render buffers are swapped, making the window
constantly render its contents, giving the illusion of animation (line 79 and 82). All rendering
code should be placed at line 80, just before the glfwSwapBuffers() method call. The last bit of
code inside the loop is a method call for GLFW to process its events, like inputs and window
events (line 84).
Outside the loop, at the bottom of the main() method declaration, the opened window is closed
and GLFW is terminated (cleaned up) (lines 90 and 92). The main function returns zero (line
98).
All of this will create a window that renders a solid blue color:

After successfully building the project, a blue window will open, like this one.
6. Troubleshooting
These are solutions to some of the errors that you may encounter while trying to build the
application:
Error Description:
The application fails to build and the following error is outputted:
LINK : warning LNK4098: defaultlib ‘MSVCRT’ conflicts with use of other libs; use
/NODEFAULTLIB:library
LINK : fatal error LNK1123: failure during conversion to COFF: file invalid or corrupt
Solution:
Just navigate to the project’s Properties and then Linker → General, at the field Enable
Incremental Linking select ‘No (/INCREMENTAL: NO)‘, like so:

At the project’s properties, select Linker → General → Enable Incremental Linking. Set it
toNO.

Error Description:
The application builds and runs fine, but there is a series of “<insert system dll name
here>.dll’Cannot find or open PDB file” right at the beginning of the output such as:
‘Test.exe': Loaded ‘C:\Windows\SysWOW64\ntdll.dll’, Cannot find or open the PDB file
‘Test.exe': Loaded ‘C:\Windows\SysWOW64\kernel32.dll’, Cannot find or open the PDB file
‘Test.exe': Loaded ‘C:\Windows\SysWOW64\KernelBase.dll’, Cannot find or open the PDB file
‘Test.exe': Loaded ‘C:\Windows\SysWOW64\opengl32.dll’, Cannot find or open the PDB file
‘Test.exe': Loaded ‘C:\Windows\SysWOW64\msvcrt.dll’, Cannot find or open the PDB file
‘Test.exe': Loaded ‘C:\Windows\SysWOW64\advapi32.dll’, Cannot find or open the PDB file

Solution:
This isn’t actually an error. It’s just a warning, telling that Visual Studio couldn’t find the files
that contain the symbols for debugging the system libraries. To “fix” that, just navigate
to: Tools →Options → Debugging → Symbols and check the Microsoft Symbol Servers option,
like this:
Simply enable that checkbox, click on OK and build the application (F7).
You will be presented with a warning message that explains that the building process might
take longer when this option is enabled. Press the OK button and OK once more, then rebuild
the project (F7). Now, it will take much longer for the application to build, because Visual
Studio C++ Express will download the missing PDB symbols.
However, you don’t have to leave this option enabled as Visual Studio C++ Express will save
the downloaded PDB files on disk, meaning that this option can be disabled after fetching the
PDB symbols from the server and after successfully building the application at least once.

Error Description:
Calling the function glGenVertexArrays() throws an exception, so the following code:

1. GLuint vertexArrayID;
2. glGenVertexArrays(1, &vertexArrayID);

Throws an exception, like this one:


Unhandled exception at 0x00000000 in Test.exe: 0xC0000005: Access violation.
Solution:
Maybe, the OpenGL implementation being requested and created for the GLFW isn’t
compatible with the called function on that specific hardware. Or probably, you have the
following code:

1. glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

So, change it to:

1. glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_COMPAT_PROFILE);

Error Description
Created window closes right after its creation.
Solution:
This is probably happening because GLEW is being initialized ( gle wInit() ) before assigning
the created OpenGL context as the current one for the window. Therefore, you have to place
the call to the gle wInit() function after the calling glfwMakeContextCurre nt().

Error Description
Right after the application starts, an error message appears stating that glew32.dll isn’t present
on the computer.
Solution:
Copy the gle w32.dll file from C:\opengl-wrappers\glew\bin\ [8] to the target folder where the
application executable is being built.

7. Additional Notes
[1] This tutorial has been tested on a Windows 7 64 bit machine with Intel HD 4000 integrated
graphics GPU and on a Windows 8 64 bit machine with a NVIDIA GTX 260 GPU. It should
work most recent Visual Studio versions.
[2] GLFW is being statically linked, at this tutorial. GLEW is being dynamically linked,
meaning you have to copy its dll to the output folder. By the time this text is being written
(Aug. 12th, 2013), there’s a newer GLEW version, which is number 1.10.0. The folder structure
in this version differs from version 1.9.0 (featured in the tutorial). But with some small
adaptations, this tutorial still works. Take a look at items #7 and #8.
[3] Download the package with precompiled libraries, not the one with the source code.
[4] The guidelines on this tutorial haven’t been tested for 64 bit applications. I’m not sure if the
process shown on this tutorial can be applied for building 64 bit applications.
[5] If your user has the privileges to access the Program Files folder, after
installing Visual C++ Express 2010 or any variation Visual Studio Express, please navigate
to C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Lib (Windows 64
bits) or C:\Program Files\Microsoft SDKs\Windows\v7.0A\Lib (Windows 32 bits). Verify if the
following files are at the aforementioned folder: OpenGL32.Lib and GLU32.Lib.
[6] Creating a Windows Console Application isn’t a requirement in order to make an OpenGL
application using GLEW and GLFW. This is being done so in this tutorial just because it’s
convenient to have a dedicated window where errors are displayed, specially errors regarding
window creation and OpenGL initialization errors. At the projection creation wizard, an Empty
Project can also be selected.
[7] If you are using GLEW version 1.10.0 and up, the folder path should be replaced with
something like C:\opengl-wrappers\glew\lib\Release\Win32.
[8] Since GLEW is being dynamically linked, you also need to copy the file gle w32.dll to your
Release directory and also bundle this DLL with the application (.exe file). If you are using
GLEW version 1.10.0 and up, the gle w32.dll file you will need to bundle with your
application is located at: C:\opengl-wrappers\glew\bin\Release\Win32 .
[9] Please refer to the GLFW documentation to see how the numbers associated with the
GLFW_CONTEXT_MAJOR and GLFW_CONTEXT_MINOR work. Also, see this
link:http://www.opengl.org/registry/specs/ARB/glx_create_context.txt .
[10] This defines the size of the rendering area of the window, without taking into the account
its borders and controls. On Windows 7, a 640×480 GLFW window is going to occupy
approximately 656×518 px if all the borders and controls are taken in account.
8. References
Other build errors might take place. But since this tutorial will definitively require future
revisions and some other types errors might occur, here are so me of the links I’ve found that
were really helpful while writing this article:
“The OpenGL Extension Wrangler Library – Installation”
at SourceForge.net :http://glew.sourceforge.net/install.html
“GLFW – Documentation – Example Code”
at GLFW.org:http://www.glfw.org/documentation.html
“Tutorial 1 – Opening a Window” at OpenGL-Tutorials.org: http://www.opengl-
tutorial.org/beginners-tutorials/tutorial-1-opening-a-window/
“Setting Up GLFW” at Shawn Deprey’s
Blog:http://shawndeprey.blogspot.com.br/2012/02/setting- up-glfw- in- visual-studio-
2010.html
“Static Compile GLFW and GLEW” at pHacks, written by Pietra
Arumaga:http://www.phacks.net/static-compile-glfw-and- glew/
“GLFW:Tutorials:Basics” at The Game Programming
Wiki:http://content.gpwiki.org/index.php?title=GLFW:Tutorials:Basics
“Setting up OpenGL, GLEW, and FreeGLUT in Visual C++” at OpenGLBook.com,
written by Eddy Luten: http://openglbook.com/setting- up-opengl- glew-and-freeglut-in-
visual-c/
“CS175, Visual Studio Setup” at CS 175 Computer Graphics course website hosted at
FAS (Faculty of Arts & Sciences) IT servers, written by Prof. Steven
Gortler:http://sites.fas.harvard.edu/~lib175/pages/visstudio.html
“Why is Visual Studio 2010 not able to find/open PDB files?” at Stack
Overflow:http://stackoverflow.com/questions/4813975/why- is-visual-studio-2010-not-
able-to-find-open-pdb-files
“Error ‘LINK : fatal error LNK1123: failure during conversion to COFF: file invalid or
corrupt’ after installing Visual Studio 2012 Release Preview” at Stack
Overflow:http://stackoverflow.com/questions/10888391/error- link-fatal-error- lnk1123-
failure-during-conversion-to-coff- file- inval
*The Visual C++ Express 2010, OpenGL, GLFW and GLEW logos are copyrighted to their
respective owners.

You might also like