通常,编译使用Dear ImGui的程序时出现链接错误是由于缺少IMGUI_IMPL_OPENGL_LOADER_GLAD宏的定义所导致的。该宏的定义告诉ImGui要使用的OpenGL库并充当加载器。以下是一个示例程序,其中包含了IMGUI_IMPL_OPENGL_LOADER_GLAD宏的定义:
#define IMGUI_IMPL_OPENGL_LOADER_GLAD
#include "imgui.h"
#include "imgui_impl_glfw.h"
#include "imgui_impl_opengl3.h"
#include // 包含glad来获取所有必需的OpenGL头文件
// 应用程序主循环
void main_loop() {
// 渲染ImGui
ImGui_ImplOpenGL3_NewFrame();
ImGui_ImplGlfw_NewFrame();
ImGui::NewFrame();
ImGui::ShowDemoWindow();
ImGui::Render();
int display_w, display_h;
glfwGetFramebufferSize(window, &display_w, &display_h);
glViewport(0, 0, display_w, display_h);
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());
// 交换缓冲区并检查是否触发事件(例如按下 ESC 键)
glfwSwapBuffers(window);
glfwPollEvents();
}
int main(int argc, char** argv)
{
// 初始化GLFW
...
// 初始化GLAD
...
// 初始化ImGui
IMGUI_CHECKVERSION();
ImGui::CreateContext();
ImGuiIO& io = ImGui::GetIO(); (void)io;
ImGui::StyleColorsDark();
ImGui_ImplGlfw_InitForOpenGL(window, true);
ImGui_ImplOpenGL3_Init("#version 330");
// 应用程序主循环
while (!glfwWindowShouldClose(window))
{
main_loop();
}
// 清理
ImGui_ImplOpenGL3_Shutdown();
ImGui_ImplGlfw_Shutdown();
ImGui::DestroyContext();
glfwTerminate();
return 0;
}