当前位置: 代码迷 >> 综合 >> Macos Clion下配置OpenGL开发环境(Setup OpenGL Development Enviroment with Clion on MacOS)
  详细解决方案

Macos Clion下配置OpenGL开发环境(Setup OpenGL Development Enviroment with Clion on MacOS)

热度:47   发布时间:2024-01-14 15:45:29.0

OpenGL开发环境 - C++ Version

  • 综述
  • 一、配置C/C++开发环境
    • step1: Install brew
    • step2: 确认自己的MacOS上安装了gcc
    • step3: 下载Clion并安装
  • 二、配置有关OpenGL的开发环境
    • homebrew下载和管理GLFW
    • GLAD 的下载与配置
      • GLAD配置要点
      • 环境变量配置
  • 三、创建与配置项目
    • CMakeLists.txt示例
  • 四、编写测试代码
  • 五、成功 效果展示

综述

在Macos上使用xcode进行openGL开发的过程比较复杂,并且一个项目需要重新配置的内容比较多,不利于重复开发。

这里我使用clion作为IDE进行openGL c++开发环境配置
好吧,我觉得有windows系统还是用visual studio写图形学代码吧
Macos写c++属实不舒适

一、配置C/C++开发环境

step1: Install brew

brew 是Macbook上用来安装和管理各种工具的的命令行工具
安装方法如下:

/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"

step2: 确认自己的MacOS上安装了gcc

gcc --version

如果没有安装的话会上面的指令会自动触发 XCode 下载并安装,根据提示安装完成之后再使用上面的指令检查一遍即可

step3: 下载Clion并安装

点击:Clion的下载路径地址
通常来说只需要安装好 gcc 即可,因为 cmake 会在 CLion 中自带,而 make 会在 MacOS 系统中提供。

以上的安装配置是针对小白的教程,相信非小白的编程者都有以上的开发环境和工具,所以接下来进入我们的主题。


二、配置有关OpenGL的开发环境

OpenGL的开发主要依赖两个库:

  • GLFW: 提供跨平台的 OpenGL 上下文初始化与窗口创建等功能
  • GLAD: Loader,作用是在程序运行时获取函数地址并将其保存在一个函数指针中供以后使用

homebrew下载和管理GLFW

我建议用homebrew来下载和管理GLFW。
因为homebrew作为统一的工具和库的管理工具,可以方便以后对库的删除和升级。这里用brew安装GLFW的命令如下:

brew install glfw

brew会默认把所有的文件安装在:

 /usr/local/Cellar/

Tips: command+shift+G再输入以上路径可直接跳转
我们可以在/usr/local/Cellar/glfw中找到所有我们安装的glfw的源代码
不仅如此,brew 还会在/usr/local/include的目录里建立一个目录软连接,这个soft link 指向了 /usr/local/Cellar/glfw/3.3/include 这个目录。这样子,GLFW的头文件就被包含在IDE默认搜索的路径下了

GLAD 的下载与配置

以下资料来自learnOpenGL-CN文档
在这里插入图片描述
官方提供了一个在线配置与生成库的网站:GLAD下载官方链接

GLAD配置要点

  • 开发语言选择:C/C++
  • API我们选择3.3
  • Profile选择Core
  • Extensions需要按ADD ALL

    Extensions需要变成如下图所示后再点击Generate

    这样我们就可以下载生成的glad.zip文件,解压后其下有include和src两个文件夹,我们借此进行环境变量配置

环境变量配置

我将解压后的glad文件夹放置到下面的路径下

/usr/local/include

即我们最后可以通过以下路径访问到glad

/usr/local/include/glad

接下来我们来配置两个环境变量:
将两条命令写入你的shell profile
如果你用的bash,可以写入 ~/. bash_profile
因为我用的是zsh,我会写入~/. zprofile文件


查看自己使用的shell版本的方法:
在终端输入:

echo $SHELL

如果显示/bin/zsh,那么就表示使用的是zsh的shell
如果显示/bin/bash,那么自然就是bash的shell
MacOS应该是从Mojave版本开始就default shell使用的是zsh
所以不管Catalina还是Big sur的用户应该都可以按照我的步骤走下去
当然也可以在终端切换:

## zsh切换bash
chsh -s /bin/bash
## bash切换zsh
chsh -s /bin/zsh

重启终端后生效


出于加载顺序的考虑,我选择编辑zprofile
阅读推荐Link:关于我们更加常使用的.zshrc和.zprofile的区别

vim ~/.zprofile

下面第一行具体的glfw后的版本号应该是会和我一致的
如果有出入,自行修改以下即可

export GLFW_HOME="/usr/local/Cellar/glfw/3.3"
export GLAD_HOME="/usr/local/include/glad"

把上边的两行放到shell profile 的最末端,然后激活shell profile

source ~/.zprofile

三、创建与配置项目

操作顺序:

  • 首先使用 CLion 创建一个 C/C++ 工程
  • 创建完成,项目根目录下出现CMakeLists.txt 文件
  • 在根目录下创建lib目录
  • 将我们刚才的glad文件夹中的glad.c放入lib文件夹

这样,我们得到的整体项目组织结构如下图所示:
项目结构

CMakeLists.txt示例

# cmake的版本号
cmake_minimum_required(VERSION 3.17)
# project 的名字
project(openGL)
# C++ version
set(CMAKE_CXX_STANDARD 11)# 检查环境变量
if (NOT DEFINED ENV{
    GLFW_HOME})message(FATAL_ERROR "found no env named GLFW_HOME")
endif()
if (NOT DEFINED ENV{
    GLAD_HOME})message(FATAL_ERROR "found no env named GLAD_HOME")
endif()# 暂存环境变量
set(GLFW_HOME $ENV{
    GLFW_HOME})
set(GLAD_HOME $ENV{
    GLAD_HOME})# 设置头文件目录
include_directories("${GLFW_HOME}/include")
include_directories("${GLAD_HOME}/include")# 添加 GLFW3 预编译库
add_library(glfw SHARED IMPORTED)
SET_TARGET_PROPERTIES(glfw PROPERTIES IMPORTED_LOCATION "${GLFW_HOME}/lib/libglfw.3.dylib")# 创建可执行文件
add_executable(openGL main.cpp "lib/glad.c")# 链接 GLFW GLAD openGL
target_link_libraries(openGL glfw "-framework OpenGL")

我的项目名定为 openGL,所以项目名如有不同,将上述文件中的openGL都换成你的项目名就可以了

四、编写测试代码

代码来自 LearnOpenGL

#include <glad/glad.h>
#include <GLFW/glfw3.h>#include <iostream>void framebuffer_size_callback(GLFWwindow* window, int width, int height);
void processInput(GLFWwindow *window);// settings
const unsigned int SCR_WIDTH = 800;
const unsigned int SCR_HEIGHT = 600;const char *vertexShaderSource = "#version 330 core\n""layout (location = 0) in vec3 aPos;\n""void main()\n""{\n"" gl_Position = vec4(aPos.x, aPos.y, aPos.z, 1.0);\n""}\0";
const char *fragmentShaderSource = "#version 330 core\n""out vec4 FragColor;\n""void main()\n""{\n"" FragColor = vec4(1.0f, 0.5f, 0.2f, 1.0f);\n""}\n\0";int main()
{
    // glfw: initialize and configure// ------------------------------glfwInit();glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);#ifdef __APPLE__glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
#endif// glfw window creation// --------------------GLFWwindow* window = glfwCreateWindow(SCR_WIDTH, SCR_HEIGHT, "LearnOpenGL", NULL, NULL);if (window == NULL){
    std::cout << "Failed to create GLFW window" << std::endl;glfwTerminate();return -1;}glfwMakeContextCurrent(window);glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);// glad: load all OpenGL function pointers// ---------------------------------------if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)){
    std::cout << "Failed to initialize GLAD" << std::endl;return -1;}// build and compile our shader program// ------------------------------------// vertex shaderint vertexShader = glCreateShader(GL_VERTEX_SHADER);glShaderSource(vertexShader, 1, &vertexShaderSource, NULL);glCompileShader(vertexShader);// check for shader compile errorsint success;char infoLog[512];glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &success);if (!success){
    glGetShaderInfoLog(vertexShader, 512, NULL, infoLog);std::cout << "ERROR::SHADER::VERTEX::COMPILATION_FAILED\n" << infoLog << std::endl;}// fragment shaderint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);glShaderSource(fragmentShader, 1, &fragmentShaderSource, NULL);glCompileShader(fragmentShader);// check for shader compile errorsglGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &success);if (!success){
    glGetShaderInfoLog(fragmentShader, 512, NULL, infoLog);std::cout << "ERROR::SHADER::FRAGMENT::COMPILATION_FAILED\n" << infoLog << std::endl;}// link shadersint shaderProgram = glCreateProgram();glAttachShader(shaderProgram, vertexShader);glAttachShader(shaderProgram, fragmentShader);glLinkProgram(shaderProgram);// check for linking errorsglGetProgramiv(shaderProgram, GL_LINK_STATUS, &success);if (!success) {
    glGetProgramInfoLog(shaderProgram, 512, NULL, infoLog);std::cout << "ERROR::SHADER::PROGRAM::LINKING_FAILED\n" << infoLog << std::endl;}glDeleteShader(vertexShader);glDeleteShader(fragmentShader);// set up vertex data (and buffer(s)) and configure vertex attributes// ------------------------------------------------------------------float vertices[] = {
    -0.5f, -0.5f, 0.0f, // left0.5f, -0.5f, 0.0f, // right0.0f,  0.5f, 0.0f  // top};unsigned int VBO, VAO;glGenVertexArrays(1, &VAO);glGenBuffers(1, &VBO);// bind the Vertex Array Object first, then bind and set vertex buffer(s), and then configure vertex attributes(s).glBindVertexArray(VAO);glBindBuffer(GL_ARRAY_BUFFER, VBO);glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0);glEnableVertexAttribArray(0);// note that this is allowed, the call to glVertexAttribPointer registered VBO as the vertex attribute's bound vertex buffer object so afterwards we can safely unbindglBindBuffer(GL_ARRAY_BUFFER, 0);// You can unbind the VAO afterwards so other VAO calls won't accidentally modify this VAO, but this rarely happens. Modifying other// VAOs requires a call to glBindVertexArray anyways so we generally don't unbind VAOs (nor VBOs) when it's not directly necessary.glBindVertexArray(0);// uncomment this call to draw in wireframe polygons.//glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);// render loop// -----------while (!glfwWindowShouldClose(window)){
    // input// -----processInput(window);// render// ------glClearColor(0.2f, 0.3f, 0.3f, 1.0f);glClear(GL_COLOR_BUFFER_BIT);// draw our first triangleglUseProgram(shaderProgram);glBindVertexArray(VAO); // seeing as we only have a single VAO there's no need to bind it every time, but we'll do so to keep things a bit more organizedglDrawArrays(GL_TRIANGLES, 0, 3);// glBindVertexArray(0); // no need to unbind it every time// glfw: swap buffers and poll IO events (keys pressed/released, mouse moved etc.)// -------------------------------------------------------------------------------glfwSwapBuffers(window);glfwPollEvents();}// optional: de-allocate all resources once they've outlived their purpose:// ------------------------------------------------------------------------glDeleteVertexArrays(1, &VAO);glDeleteBuffers(1, &VBO);glDeleteProgram(shaderProgram);// glfw: terminate, clearing all previously allocated GLFW resources.// ------------------------------------------------------------------glfwTerminate();return 0;
}// process all input: query GLFW whether relevant keys are pressed/released this frame and react accordingly
// ---------------------------------------------------------------------------------------------------------
void processInput(GLFWwindow *window)
{
    if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS)glfwSetWindowShouldClose(window, true);
}// glfw: whenever the window size changed (by OS or user resize) this callback function executes
// ---------------------------------------------------------------------------------------------
void framebuffer_size_callback(GLFWwindow* window, int width, int height)
{
    // make sure the viewport matches the new window dimensions; note that width and// height will be significantly larger than specified on retina displays.glViewport(0, 0, width, height);
}

五、成功 效果展示

  相关解决方案