VSCode OpenGL 环境搭建

发布时间:2024年01月19日

目录

下载glfw、glad、安装vscode插件C/C++ Project Generator

下载glfw?Download | GLFW

下载 glad?https://glad.dav1d.de/

vscode 插件安装: C/C++ Project Generator

创建C++项目:commond+p

项目结构如下图:

添加glfw、glad

添加glfw

头文件加入 GLFW 拖到项目的include目录下

加入libglfw.3.dylib? 到 lib目录下

添加glad

把glad.c 编译成静态库 glad.a

添加glad的头文件

添加完glfw、glad后的文件结构

修改 makefile文件

添加动态库、静态库搜索路径

添加动态库名、静态库名

完整的Makefile

在main.cpp 中添加openGL 代码

main中完整代码

运行:make run??

注意:


下载glfw、glad、安装vscode插件C/C++ Project Generator

下载glfw?Download | GLFW

下载 glad?https://glad.dav1d.de/

vscode 插件安装: C/C++ Project Generator

创建C++项目:commond+p

选择 Create C++ project? ?回车即创建成功。

运行:make run

编译:make

清除:make clean

项目结构如下图:

添加glfw、glad

添加glfw

头文件加入 GLFW 拖到项目的include目录下

加入libglfw.3.dylib? 到 lib目录下

apple? chip 芯片(m1、m2):选择 lib-arm64的libglfw.3.dylib

inter? chip 芯片:? 选择 lib-x86_64的libglfw.3.dylib

添加glad

把glad.c 编译成静态库 glad.a

  • 生成可执行文件 glad.o? ? ? ?先cd 到glad目录下,执行:在glad目录下会生成? glad.o 文件
gcc  -c  ./src/glad.c   -I   ./include/
  • 生成glad.a 静态库文件 。执行
ar rcs? ?glad.a? ? glad.o
  • 添加glad.a 文件到项目的lib目录 中

添加glad的头文件

拷贝glad的include中的glad目录、KHR目录到项目的include目录下

添加完glfw、glad后的文件结构

修改 makefile文件

添加动态库、静态库搜索路径

# 自定义库路径

# -Wl,-rpath, 后面跟动态库路径目录 动态库文件 .dylib

# -L 后面跟静态库文件 .a

LFLAGS = -Wl,-rpath,/Users/leiming/OpenGL/VScodeOpenGL/lib/ -L/Users/leiming/OpenGL/VScodeOpenGL/lib/

添加动态库名、静态库名

# 定义库文件

# 添加库 -lX X=>libglad.a 去掉lib与.a 即 -lglad

# 添加库 libglfw.3.dylib =>去掉lib与.dylib 即 -glfw.3

LIBRARIES	:=   -lglad  -lglfw.3

完整的Makefile

#
# 'make'        编译生成可执行文件 main
# 'make clean'  删除所的.o和可执行文件
# 'make run'   编译并执行

# 指定编译器
CXX = g++

# 编译时的标志  使用c++17 标准  警告消息
CXXFLAGS	:= -std=c++17 -Wall -Wextra -g

# 自定义库路径
# -Wl,-rpath,   后面跟动态库路径目录   动态库文件  .dylib
# -L   后面跟静态库文件 .a 
LFLAGS = -Wl,-rpath,/Users/leiming/OpenGL/VScodeOpenGL/lib/ -L/Users/leiming/OpenGL/VScodeOpenGL/lib/

# 定义输出目录
OUTPUT	:= output

# 定义源文件目录
SRC		:= src

# 定义头文件目录
INCLUDE	:= include

# 定义库文件目录
LIB		:= lib
# 定义库文件 
# 添加库 -lX   X=>libglad.a  去掉lib与.a 即 -lglad
# 添加库 libglfw.3.dylib   =>去掉lib与.dylib  即 -glfw.3
LIBRARIES	:=   -lglad  -lglfw.3   # add

ifeq ($(OS),Windows_NT)
MAIN	:= main.exe
SOURCEDIRS	:= $(SRC)
INCLUDEDIRS	:= $(INCLUDE)
LIBDIRS		:= $(LIB)
FIXPATH = $(subst /,\,$1)
RM			:= del /q /f
MD	:= mkdir
else
MAIN	:= main
SOURCEDIRS	:= $(shell find $(SRC) -type d)
INCLUDEDIRS	:= $(shell find $(INCLUDE) -type d)
LIBDIRS		:= $(shell find $(LIB) -type d)
FIXPATH = $1
RM = rm -f
MD	:= mkdir -p
endif

# define any directories containing header files other than /usr/include
INCLUDES	:= $(patsubst %,-I%, $(INCLUDEDIRS:%/=%))

# define the C libs
LIBS		:= $(patsubst %,-L%, $(LIBDIRS:%/=%))

# define the C source files
SOURCES		:= $(wildcard $(patsubst %,%/*.cpp, $(SOURCEDIRS)))

# define the C object files
OBJECTS		:= $(SOURCES:.cpp=.o)

# define the dependency output files
DEPS		:= $(OBJECTS:.o=.d)

#
# The following part of the makefile is generic; it can be used to
# build any executable just by changing the definitions above and by
# deleting dependencies appended to the file from 'make depend'
#
WLDir := -Wl,-rpath,/Users/leiming/OpenGL/VScodeOpenGL/lib/
LLIBDir := -L/Users/leiming/OpenGL/VScodeOpenGL/lib/

OUTPUTMAIN	:= $(call FIXPATH,$(OUTPUT)/$(MAIN))

all: $(OUTPUT) $(MAIN)
	@echo Executing 'all' complete!

$(OUTPUT):
	$(MD) $(OUTPUT)

$(MAIN): $(OBJECTS)
	$(CXX) $(CXXFLAGS) $(INCLUDES) -o $(OUTPUTMAIN) $(OBJECTS) $(LFLAGS)  $(LIBS) $(LIBRARIES)

# include all .d files
-include $(DEPS)

# this is a suffix replacement rule for building .o's and .d's from .c's
# it uses automatic variables $<: the name of the prerequisite of
# the rule(a .c file) and $@: the name of the target of the rule (a .o file)
# -MMD generates dependency output files same name as the .o file
# (see the gnu make manual section about automatic variables)
.cpp.o:
	$(CXX) $(CXXFLAGS) $(INCLUDES) -c -MMD $<  -o $@

.PHONY: clean
clean:
	$(RM) $(OUTPUTMAIN)
	$(RM) $(call FIXPATH,$(OBJECTS))
	$(RM) $(call FIXPATH,$(DEPS))
	@echo Cleanup complete!

run: all
	./$(OUTPUTMAIN)
	@echo Executing 'run: all' complete!

在main.cpp 中添加openGL 代码

你好,三角形 - LearnOpenGL CN

main中完整代码

#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 shader
    unsigned int vertexShader = glCreateShader(GL_VERTEX_SHADER);
    glShaderSource(vertexShader, 1, &vertexShaderSource, NULL);
    glCompileShader(vertexShader);
    // check for shader compile errors
    int 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 shader
    unsigned int fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
    glShaderSource(fragmentShader, 1, &fragmentShaderSource, NULL);
    glCompileShader(fragmentShader);
    // check for shader compile errors
    glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &success);
    if (!success)
    {
        glGetShaderInfoLog(fragmentShader, 512, NULL, infoLog);
        std::cout << "ERROR::SHADER::FRAGMENT::COMPILATION_FAILED\n"
                  << infoLog << std::endl;
    }
    // link shaders
    unsigned int shaderProgram = glCreateProgram();
    glAttachShader(shaderProgram, vertexShader);
    glAttachShader(shaderProgram, fragmentShader);
    glLinkProgram(shaderProgram);
    // check for linking errors
    glGetProgramiv(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, // left
        0.5f, -0.5f, 0.0f,  // right
        0.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 unbind
    glBindBuffer(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 triangle
        glUseProgram(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 organized
        glDrawArrays(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);
}

运行:make run??

注意:

libgflw.3.dylib 会提示无法打开、恶意之类的提示 ,可以到mac的设置的隐私与安全中选择打开?libgflw.3.dylib

文章来源:https://blog.csdn.net/z1067832450_/article/details/135697429
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。