1. 程式人生 > >Mac 上的 GLFW 環境配置

Mac 上的 GLFW 環境配置

背景:GLFW

一、下載和編譯

  1. 從官網下載原始碼包:http://www.glfw.org/download.html
    (我下載的是 github 倉庫上的)

  2. 官方指南編譯。總結如下:

cd glfw-master
cmake . 
# 預設是編譯靜態庫,如果要編譯動態庫則 cmake -DBUILD_SHARED_LIBS=ON .
make
make install

最後會看到

Install the project...
-- Install configuration: ""
-- Installing: /usr/local/include/GLFW
-- Installing: /usr/local/include/GLFW/glfw3.h
-- Installing: /usr/local/include/GLFW/glfw3native.h
-- Installing: /usr/local/lib/cmake/glfw3/glfw3Config.cmake
-- Installing: /usr/local/lib/cmake/glfw3/glfw3ConfigVersion.cmake
-- Installing: /usr/local/lib/cmake/glfw3/glfw3Targets.cmake
-- Installing: /usr/local/lib/cmake/glfw3/glfw3Targets-noconfig.cmake
-- Installing: /usr/local/lib/pkgconfig/glfw3.pc
-- Installing: /usr/local/lib/libglfw3.a

二、配置 XCode 專案

注:配置名字可以通過cmd+f搜尋來定位

  1. 配置專案的Build Settings:

    • Other Linker Flags 為 -lgfw3

    • Library Search Paths 的 Debug 和 Release 分別加上/usr/local/lib/

    • Header Search Paths 加上 /usr/local/include/

  2. 新增庫,開啟專案的Build Phases

    在 Link Binary With Libraries 中新增:

    • Cocoa

    • OpenGL

    • IOKit

    • CoreVideo

三、編譯程式碼

新建main.cpp:

#include <GLFW/glfw3.h>

int main(int argc, const char * argv[]) {
    GLFWwindow* win;
    if(!glfwInit()){
        return -1;
    }
    win = glfwCreateWindow(640, 480, "OpenGL Base Project", NULL, NULL);
    if(!win)
    {
        glfwTerminate();
        return -1;
    }
    glfwMakeContextCurrent(win);
    while(!glfwWindowShouldClose(win)){
        glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
        glClear(GL_COLOR_BUFFER_BIT);
        glBegin(GL_TRIANGLES);
        {
            glColor3f(1.0,0.0,0.0);
            glVertex2f(0, .5);
            glColor3f(0.0,1.0,0.0);
            glVertex2f(-.5,-.5);
            glColor3f(0.0, 0.0, 1.0);
            glVertex2f(.5, -.5);
        }
        glEnd();
        glfwSwapBuffers(win);
        glfwPollEvents();
    }
    glfwTerminate();
    return 0;
}

點選執行按鈕。效果如下:

OpenGL 教程推薦:https://learnopengl-cn.github.io