Search code examples
windowswinapiopenglcross-platform

Why is Windows.h required for the use of OpenGL functions?


I am working on an app that uses OpenGL to make a simple game. Just starting to learn OpenGL. Why, in the code snippet below, do I need <Windows.h> to recognise GLuint vao? Removing the include causes an error.

#include <Windows.h>
#include <gl/GL.h>

int main() {
    GLuint vao;
}

I get 868 errors when I remove the include <Windows.h>. Errors like 'APIENTRY': this use of 'void' is not valid, int APIENTRY: redefinition, int WINGDIAPI: redefinition and honestly a lot more.

I am developing on Windows, but this would automatically mean cross-platform is impossible without some external toolkit/library like GLEW, GLUT etc.? I know they are strongly advised but for reasons, I cannot use them.

Also, does that mean I need to include <Windows.h> in every file where I use OpenGL functions? That would not make very good practice, I think.


Solution

  • On Windows, including Windows.h before including GL.h is required.

    But the actual problem is not the definition of GLuint which is defined in GL.h, but that all methods defined in GL.h require the definition of the WINGDIAPI and the APIENTRY macro. WINGDIAPI tells the compiler that the method has to be loaded from a dll (which is per-se Window specific) and is defined in wingdi.h. APIENTRY is defined in minwindef.h. Both are both included by Windows.h.

    About cross-platform: The problem is that while the OpenGL API is (in general) platform independent, the OpenGL implementation as well as OpenGL context handling is not. Different systems do not even use the same OpenGL header file. MacOS, for example, uses OpenGL/gl.h while Windows uses GL/gl.h. Other example, a OpenGL context is created on Windows through the wgl API while some other systems use glx. If you want to develop cross-platform, you either need to abstract all of that yourself, or you use one of the libraries (glfw, glew) that already do that for you.