在VS2022中搭建OpenGL环境
GLFW是一个专门针对OpenGL的C语言库,它提供了渲染所需的一些接口,允许用户创建OpenGL上下文、定义窗口参数以及处理用户输入等。网上教程虽然多但有些比较复杂,有些提供的不全,所有记录一下,便于自己和初学者参考
- 1. 新建项目
新建cpp文件:
右键项目名–》点击添加—》添加项 - 2. 下载glfw
下载glfw的网页地址:https://www.glfw.org/download.html
将下载文件放到你想放的位置,然后将下载后的文件解压,新建一个文件夹,将glfw中的include文件和你对应的lib-vs(版本号)复制到该文件夹中。我的VS使用的是2022版本的,所以我复制的是lib-vs2022,文件夹内容如下:
- 3. 对创建项目的opengl进行配置
注意2中文件夹路径为:F:\opengl\Dependencies\GLFW
vs中配置如下:
右键项目名–》点击属性 进入到如下界面:
- 4. 添加代码:
#include <GLFW/glfw3.h>
int main()
{
GLFWwindow* window;
/* Initialize the library */
if (!glfwInit())
return -1;
/* Create a windowed mode window and its OpenGL context */
window = glfwCreateWindow(640, 480, "Hello World", NULL, NULL);
if (!window)
{
glfwTerminate();
return -1;
}
float positions[6] = {
-0.5f, -0.5f,
0.0f, 0.5f,
0.5f, -0.5f
};
/* Make the window's context current */
glfwMakeContextCurrent(window);
//glewInit();
unsigned int buffer;
/*glGenBuffers(1, &buffer);
glBindBuffer(GL_ARRAY_BUFFER, buffer);
glBufferData(GL_ARRAY_BUFFER, 6 * sizeof(float), positions, GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);*/
/* Loop until the user closes the window */
while (!glfwWindowShouldClose(window))
{
/* Render here */
glClear(GL_COLOR_BUFFER_BIT);
glBegin(GL_TRIANGLES);
glVertex2f(-0.5f, -0.5f);
glVertex2f(0.0f, 0.5f);
glVertex2f(0.5f, -0.5f);
glEnd();
/* Swap front and back buffers */
glfwSwapBuffers(window);
/* Poll for and process events */
glfwPollEvents();
}
glfwTerminate();
return 0;
}
- 5. 结果图