如何在 Linux 中使用 GLFW 函数正确链接 C++ 对象?

How to correctly link C++ objects using GLFW functions in Linux?

提问人:rvvermeulen 提问时间:6/3/2018 更新时间:6/3/2018 访问量:258

问:

我创建了一个包含多个文件的非常简单的程序,现在正在尝试将 GLFW 库链接到它。我只将 GLFW 函数添加到文件 main.cpp 中,并且只包含其中的库,并且只有使用命令编译和执行此文件才能正常工作。g++ main.cpp -lglfw

在我添加这个库之前,编译和链接整个程序也很顺利,但是即使其他文件中没有使用 GLFW 函数,当我想将所有内容链接在一起时 () 我突然收到错误“未定义引用”我使用的每个 GLFW 函数。(我在编译main.cpp时没有错误:g++ -Wall -g -std=c++11 -lglfw main.o hello_world.o console.og++ -Wall -g -std=c++11 -lglfw -c main.cpp)

这是文件 main.cpp:

#include "basis.h"
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <string>
// Open-GL
#include <GLFW/glfw3.h>
/// Setup:
/// sudo apt-get update
/// sudo apt-get install libglfw3
/// sudo apt-get install libglfw3-dev
/// Compile:
/// g++ main.cpp -lglfw

using namespace std;

void errorCallback(int error, const char* description) {
    fprintf(stderr, "Error: %s\n", description);
}

void test() {
    GLFWwindow* window = glfwCreateWindow(640, 480, "My Title", NULL, NULL);
    if (!window) {
        cout << "Window creation failed!" << endl;
    }
    runConsole();
}

int main(int argc, char* argv[]) {
    glfwSetErrorCallback(errorCallback);
    if (!glfwInit()) {
        cout << "GLFW initialization failed!" << endl;
        exit(EXIT_FAILURE);
    }

    test();

    glfwTerminate();
    return 0;
}

此外,我不知道库在我的机器上的位置。此外,Linux 机器是 Virtual Box,源代码位于我的主机 Windows 系统上的共享文件夹中,但这在我之前在 Linux 上编译库时从未产生过问题。

C++ Linux 链接器错误 glfw 未定义引用

评论

0赞 Galik 6/3/2018
如果已安装,则可以在链接命令的末尾使用pkg-config$(pkg-config glfw3 --libs)

答:

1赞 rvvermeulen 6/3/2018 #1

哎呀,在重新阅读这个问题时,我想到了一个新的解决方案,它:)正确的链接器命令是:g++ -Wall -g -std=c++11 main.o hello_world.o console.o -lglfw