How do you create a window in Linux with C++?
For OpenGL, the easiest way to do it is by using GLUT or SDL. Here's an approximate example using GLUT:
#include <GL/glut.h>
int main (int argc, char **argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH);
glutInitWindowSize(800, 600);
glutInitWindowPosition(100, 100);
glutCreateWindow("My new window");
/* ... */
}
You really want to avoid using Xlib directly as it's extremely tedious to use. Furthermore, GLUT and SDL make it easier to port your OpenGL application to different platforms.
The X window system generally does the drawing - you then use a toolkit such as Qt or GTK on top of raw Xlib to provide event loops, drag and drop, starting apps on mouseclicks and all the other 'desktop' stuff
It's fairly easy to work directly with Xlib and opengl or if you just want to learn opengl the glut provides the framework you need to display a window, handle mouse/keyboard events and so on.
Updated answer for 2019. Unix like systems normally uses the X window system. You can work with it directly using Xlib this is the low level API. But you likely need a more welcoming and cross-platform solution. You can use:
- OpenGL Utility Toolkit - GLUT
- Simple and Fast Multimedia Library - SFML
- Simple DirectMedia Layer - SDL
- Graphics Library Framework - GLFW (my recommendation)
GLFW is written in C and has native support for Windows, macOS and many Unix-like systems using the X Window System, such as Linux and FreeBSD.
Once installed, create a window with :
#include <GLFW/glfw3.h>
.
. //Entry and glfwInit()
.
GLFWwindow* window = glfwCreateWindow(1000, 1000, "MyWindow", NULL, NULL);
glfwMakeContextCurrent(window);