用cmake怎么编译一个用glad的工程
时间: 2024-05-15 11:16:40 浏览: 150
以下是使用CMake编译使用GLAD的工程的步骤:
1. 在工程目录下创建一个CMakeLists.txt文件,内容如下:
```cmake
cmake_minimum_required(VERSION 3.10)
project(MyProject)
# 添加可执行文件
add_executable(MyProject main.cpp)
# 添加GLAD库
add_subdirectory(glad)
include_directories(glad/include)
target_link_libraries(MyProject glad)
# 添加其他依赖库
# target_link_libraries(MyProject ...)
```
2. 在工程目录下创建一个glad目录,并在glad目录下下载GLAD库。
3. 在glad目录下再创建一个CMakeLists.txt文件,内容如下:
```cmake
add_library(glad src/glad.c)
```
4. 在工程目录下创建main.cpp文件,内容如下:
```cpp
#include <glad/glad.h>
#include <GLFW/glfw3.h>
#include <iostream>
void framebuffer_size_callback(GLFWwindow* window, int width, int height);
void processInput(GLFWwindow *window);
// 设置窗口大小
const unsigned int SCR_WIDTH = 800;
const unsigned int SCR_HEIGHT = 600;
int main()
{
// 初始化GLFW
glfwInit();
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
// 创建窗口
GLFWwindow* window = glfwCreateWindow(SCR_WIDTH, SCR_HEIGHT, "MyProject", 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
if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress))
{
std::cout << "Failed to initialize GLAD" << std::endl;
return -1;
}
// 渲染循环
while (!glfwWindowShouldClose(window))
{
processInput(window);
// 渲染指令
glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
// 交换缓冲区
glfwSwapBuffers(window);
glfwPollEvents();
}
// 清理资源
glfwTerminate();
return 0;
}
void framebuffer_size_callback(GLFWwindow* window, int width, int height)
{
glViewport(0, 0, width, height);
}
void processInput(GLFWwindow *window)
{
if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS)
glfwSetWindowShouldClose(window, true);
}
```
5. 在工程目录下打开命令行终端,执行以下命令:
```bash
mkdir build
cd build
cmake ..
make
```
6. 编译完成后,在build目录下会生成可执行文件MyProject。运行该可执行文件即可看到一个黑色的窗口。
阅读全文