在上一篇博客裏已經介紹過有關OpenGL和GLFW的內容了,現在開始安裝並使用GLFW來運行第一個OpenGL的例子。
操作系統
MacOS 10.13.1
因爲Xcode太大了,動不動就更新,所以我已經不用Xcode了,使用命令行工具gcc/g++來編譯,下面的程序就是使用命令行進行鏈接庫和編譯的。
首先確定Mac裏的命令行工具可用,使用命令 gcc --version
:
$ gcc --version
Configured with: --prefix=/Library/Developer/CommandLineTools/usr --with-gxx-include-dir=/usr/include/c++/4.2.1
Apple LLVM version 9.0.0 (clang-900.0.38)
Target: x86_64-apple-darwin17.2.0
Thread model: posix
InstalledDir: /Library/Developer/CommandLineTools/usr/bin
如果沒有gcc,需要自行安裝。
OpenGL的核心庫系統裏都自帶了,感興趣的可以去目錄 /System/Library/Frameworks/OpenGL.framework/
裏看一下。
然後使用homebrew來安裝 GLFW,如果沒安裝homebrew的需要先安裝一下。
$ brew install glfw3
下載完就安裝好了!
/usr/local/Cellar/
目錄下會多出來一個 glfw
的文件夾,相關的文件都在這個裏面。
使用的時候引入頭文件 glfw3.h
,然後鏈接庫 glfw
就可以了。
運行OpenGL第一個例子
在網上覆制一段代碼,保存成文件 test.c
#include <GLFW/glfw3.h>
int main(void)
{
GLFWwindow* window;
/* Initialize the library */
if (!glfwInit())
return -1;
/* Create a windowed mode window and its OpenGL context */
window = glfwCreateWindow(480, 320, "Hello World", NULL, NULL);
if (!window)
{
glfwTerminate;
return -1;
}
/* Make the window's context current */
glfwMakeContextCurrent(window);
/* Loop until the user closes the window */
while (!glfwWindowShouldClose(window))
{
/* Draw a triangle */
glBegin(GL_TRIANGLES);
glColor3f(1.0, 0.0, 0.0); // Red
glVertex3f(0.0, 1.0, 0.0);
glColor3f(0.0, 1.0, 0.0); // Green
glVertex3f(-1.0, -1.0, 0.0);
glColor3f(0.0, 0.0, 1.0); // Blue
glVertex3f(1.0, -1.0, 0.0);
glEnd();
/* Swap front and back buffers */
glfwSwapBuffers(window);
/* Poll for and process events */
glfwPollEvents();
}
}
編譯成可執行文件:
$ gcc test.c -o run -lglfw -framework OpenGL
運行:
./run
Bingo~