Hello OpenGL

VSCode + GLFW + GLEW 在ubuntu下的安装

环境说明

  • 开发环境:Linux
  • 运行环境:Linux
  • 运行方式:
    • 首先在/HelloOpenGL文件夹(本文件夹)下打开终端,用export LD_LIBRARY_PATH=./../dll,增加动态库搜索路径
    • 运行可执行文件./helloOpenGL
    • 若失败,则按照GLFW、GLEW的配置方法配置好环境后在本机重新编译
  • 使用库:GLFW、GLEW、GLM

    安装

    OpenGL(包括GLUT):

    1
    2
    3
    sudo apt-get install build-essential libgl1-mesa-dev
    sudo apt-get install freeglut3-dev
    sudo apt-get install libglew-dev libsdl2-dev ibsdl2-image-dev libglm-dev libfreetype6-dev

GLFW:

  1. 官网下载源码
  2. 编译安装:

    • 安装cmake: sudo apt-get install cmake
    • 解压刚刚下载的源码: sudo unzip xxx.zip -d glfw,其中xxx为你刚刚下载的压缩包名
    • 进入解压后的GLFW根目录(含有include、CMake的那个),进行安装:
      1
      2
      3
      sudo cmake .
      sudo make
      sudo make install

GLEW:

  • 查看glew:sudo apt-cache search glew
  • 将显示的内容用sudo apt-get install xxx下载下来,其中xxx为要下载的内容

编译

1
g++ -o helloOpenGL helloOpenGL.cpp -lGL -lGLU -lglut -lglfw3 -lX11 -lXrandr -lXinerama -lXi -lXxf86vm -lXcursor -lpthread -lGLEW -ldl

实例源码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <iostream>
using namespace std;

// Is called whenever a key is pressed/released via GLFW
void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode)
{
if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)
glfwSetWindowShouldClose(window, GL_TRUE);
}

int main(void)
{
GLFWwindow* window;

/* Initialize the library */
if (!glfwInit())
return -1;

/* Create a windowed mode window and its OpenGL context */
window = glfwCreateWindow(800, 600, "The First Opengl Program", NULL, NULL);
if (!window)
{
glfwTerminate();
return -1;
}

// Set the required callback functions 设置事件回调函数
glfwSetKeyCallback(window, key_callback);

/* Make the window's context current */
glfwMakeContextCurrent(window);

/* Loop until the user closes the window */
while (!glfwWindowShouldClose(window))
{
/* Draw a triangle */
glBegin(GL_QUAD_STRIP);

glVertex3f(0.5, 0.5, 0.0);

glVertex3f(0.5, -0.5, 0.0);

glVertex3f(-0.5, 0.5, 0.0);

glVertex3f(-0.5, -0.5, 0.0);


glEnd();

/* Swap front and back buffers */
glfwSwapBuffers(window);

/* Poll for and process events */
glfwPollEvents();
}

glfwTerminate();
return 0;
}

效果

helloOpenGL-result

注意事项

  1. GLEW应该在GLFW、GLUT等之前include。
  2. 要加上-ldl,否则会出现错误:

    1
    2
    /usr/bin/x86_64-linux-gnu-ld: //usr/local/lib/libglfw3.a(vulkan.c.o): undefined reference to symbol 'dlclose@@GLIBC_2.2.5'
    //lib/x86_64-linux-gnu/libdl.so.2: error adding symbols: DSO missing from command line
  3. 由于很多教程基于GLUT,又有很多教程基于GLFW、GLEW,因此编译连接了大部分可能用到的库

  4. 若不调用GLEW,很有可能造成shader的许多问题

参考来源:

关于GLEW的错误

GLFW的安装

GLEW的安装

OpenGL下载安装+GLEW的include顺序问题

OpenGL环境配置

渲染器

绘制demo