How do I use SDL/GLFW for cross-platform windows?

C++ with SDL and GLFW allows developers to create cross-platform applications with ease. SDL provides low-level access to audio, keyboard, mouse, joystick, and graphics hardware via OpenGL and Direct3D. GLFW, on the other hand, is specifically designed to create windows and manage OpenGL contexts. By using both, you can develop powerful applications that work across various platforms like Windows, Linux, and macOS.

This example demonstrates how to create a simple window using GLFW and render a triangle with OpenGL.

#include <GL/glew.h> #include <GLFW/glfw3.h> #include <iostream> void setupTriangle() { GLfloat vertices[] = { 0.0f, 0.5f, // Top -0.5f, -0.5f, // Bottom left 0.5f, -0.5f // Bottom right }; GLuint VBO, VAO; glGenVertexArrays(1, &VAO); glGenBuffers(1, &VBO); glBindVertexArray(VAO); glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(GLfloat), (GLvoid*)0); glEnableVertexAttribArray(0); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindVertexArray(0); } int main() { if (!glfwInit()) { std::cerr << "Failed to initialize GLFW" << std::endl; return -1; } GLFWwindow* window = glfwCreateWindow(800, 600, "Simple OpenGL with GLFW", NULL, NULL); if (!window) { std::cerr << "Failed to create GLFW window" << std::endl; glfwTerminate(); return -1; } glfwMakeContextCurrent(window); glewExperimental = GL_TRUE; if (glewInit() != GLEW_OK) { std::cerr << "Failed to initialize GLEW" << std::endl; return -1; } setupTriangle(); while (!glfwWindowShouldClose(window)) { glClear(GL_COLOR_BUFFER_BIT); glBindVertexArray(VAO); glDrawArrays(GL_TRIANGLES, 0, 3); glBindVertexArray(0); glfwSwapBuffers(window); glfwPollEvents(); } glfwTerminate(); return 0; }

C++ SDL GLFW cross-platform OpenGL graphics window Linux Windows macOS