首页 > 解决方案 > 在 Linux 上编译和运行 GLFW

问题描述

我试图设置 GLFW,以便可以在 C++ 中制作 Windows,但遇到了问题。我的问题是每次编译时都会出错。我试图让一个窗口在我终止它时打开和关闭。我已经尝试了多种方法来解决这个问题,但实际上没有一种方法能正常工作。我真的不知道我是否错误地编译了 GLFW,我的 CMake 文件是否错误,或者我尝试这样做的方式是愚蠢的。

这是代码:

#include <GLFW/glfw3.h>

int main(void)
{
    GLFWwindow* window;

    /* Initialize the library */
    if (!glfwInit())
        return -1;

    /* Create a windowed mode window and its OpenGL context */
    window = glfwCreateWindow(640, 480, "Hello World", NULL, NULL);
    if (!window)
    {
        glfwTerminate();
        return -1;
    }

    /* Make the window's context current */
    glfwMakeContextCurrent(window);

    /* Loop until the user closes the window */
    while (!glfwWindowShouldClose(window))
    {
        /* Render here */
        glClear(GL_COLOR_BUFFER_BIT);

        /* Swap front and back buffers */
        glfwSwapBuffers(window);

        /* Poll for and process events */
        glfwPollEvents();
    }

    glfwTerminate();
    return 0;
}

我尝试运行代码时收到的错误消息:

-- Configuring done
-- Generating done
-- Build files have been written to: /home/user/Documents/CPP-Stuff/OpenGL-Learning
[2/2] Linking CXX executable opengl-learning
FAILED: opengl-learning 
: && /usr/bin/c++  -Wall -Werror -std=c++14 -g   CMakeFiles/opengl-learning.dir/src/main.cpp.o  -o opengl-learning  -lglfw && :
/usr/bin/ld: CMakeFiles/opengl-learning.dir/src/main.cpp.o: in function `main':
/home/user/Documents/CPP-Stuff/OpenGL-Learning/src/main.cpp:26: undefined reference to `glClear'
collect2: error: ld returned 1 exit status
ninja: build stopped: subcommand failed.

CMake 文件 (CMakeLists.txt):

cmake_minimum_required (VERSION 3.5)

project (opengl-learning)

find_package(PkgConfig REQUIRED)
pkg_search_module(GLFW REQUIRED glfw3)
include_directories(${GLFW_INCLUDE_DIRS})

set (GCC_COVERAGE_LINK_FLAGS "-lglfw3 -lGL -lX11 -lpthread -lXrandr -lXi -ldl")

add_definitions(${GCC_COVERAGE_COMPILE_FLAGS})

set (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Werror -std=c++14")
set (source_dir "${PROJECT_SOURCE_DIR}/src/")

file (GLOB source_files "${source_dir}/*.cpp")

add_executable (opengl-learning ${source_files})

target_link_libraries(opengl-learning ${GLFW_LIBRARIES})

我正在运行构建项目的 build.sh 文件:

#!/bin/sh

cmake -G "Ninja" -DCMAKE_BUILD_TYPE=Debug
ninja

最后是 GLFW 的 /usr/include/ 中的文件: 文件

(哦,而且,我安装的唯一依赖项是xorg-dev,如果这很重要。我不确定是否还有其他必需的依赖项。)

我发现如果我注释掉`glClear',它会编译,但是当我尝试运行它时,什么也没有发生。该程序只是终止而不向终端输出任何内容或打开窗口。如果有人知道如何解决这个问题,请告诉我。

标签: c++linuxopenglcmakeglfw

解决方案


您的代码中没有包含任何 OpenGL 加载程序。glClear是一个OpenGL函数。看看高兴


推荐阅读