1. 程式人生 > >GLFW+GLEW搭建opengl環境(備忘)

GLFW+GLEW搭建opengl環境(備忘)

使用VS2017社群版本(免費版)

下載GLFW和GLEW原始碼。

使用CMAKE生成工程檔案

開啟右擊GLFW和GLEW專案編譯

GLFW預設是靜態庫

編譯GLEW時調整為靜態庫。將生成的lib和原始碼中的include資料夾放好,新建空的C++專案。在專案屬性設定好路徑。

 

 

opengl32.lib包含在window sdk 10中了。不需要單獨編譯。

 

為了支援中文需要使用UTF-8無bom編碼。測試程式碼如下。

#include <iostream>    
// GLEW    
#define GLEW_STATIC    
#include 
<GL/glew.h> #include <Windows.h> // GLFW #include <GLFW/glfw3.h> #pragma comment(lib,"winmm.lib") // 告訴聯結器與這個庫連線,因為我們要播放多媒體聲音 #pragma comment(linker, "/subsystem:\"windows\" /entry:\"mainCRTStartup\"" ) //#define DEBUG // Function prototypes void key_callback(GLFWwindow* window, int
key, int scancode, int action, int mode); // Window dimensions const GLuint WIDTH = 800, HEIGHT = 600; // The MAIN function, from here we start the application and run the game loop //#ifdef DEBUG //int main() //#else //int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR szCmdLine, int iCmdShow)
//#endif int main() { std::cout << "Starting GLFW context, OpenGL 3.3" << std::endl; // Init GLFW glfwInit(); // Set all the required options for GLFW glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_RESIZABLE, GL_FALSE); // Create a GLFWwindow object that we can use for GLFW's functions GLFWwindow* window = glfwCreateWindow(WIDTH, HEIGHT,"墨跡",nullptr, nullptr); if (window == nullptr) { std::cout << "Failed to create GLFW window" << std::endl; glfwTerminate(); return -1; } glfwMakeContextCurrent(window); // Set the required callback functions glfwSetKeyCallback(window, key_callback); // Set this to true so GLEW knows to use a modern approach to retrieving function pointers and extensions glewExperimental = GL_TRUE; // Initialize GLEW to setup the OpenGL Function pointers if (glewInit() != GLEW_OK) { std::cout << "Failed to initialize GLEW" << std::endl; return -1; } // Define the viewport dimensions glViewport(0, 0, WIDTH, HEIGHT); // Game loop while (!glfwWindowShouldClose(window)) { // Check if any events have been activiated (key pressed, mouse moved etc.) and call corresponding response functions glfwPollEvents(); // Render // Clear the colorbuffer glClearColor(0.2f, 0.3f, 0.3f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); // Swap the screen buffers glfwSwapBuffers(window); Sleep(20); } // Terminate GLFW, clearing any resources allocated by GLFW. glfwTerminate(); return 0; } // Is called whenever a key is pressed/released via GLFW void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode) { std::cout << key << std::endl; if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS) glfwSetWindowShouldClose(window, GL_TRUE); }

效果如下

程式400kb,無需動態庫。

 

單獨一個程式的話會比動態庫要小。