链接器问题返回未定义的引用

C++, Linker Issue returning undefined reference

本文关键字:引用 未定义 返回 问题 链接      更新时间:2023-10-16

这可能是重复的,但是我所看到的所有问题的答案都没有充分回答我的问题,所以我还是发了。

我的代码就是这样。非常基本的。从其他网站复制粘贴。

#include <GL/glew.h> // include GLEW and new version of GL on Windows
#include <GLFW/glfw3.h> // GLFW helper library
#include <stdio.h>
int main() {
  // start GL context and O/S window using the GLFW helper library
  if (!glfwInit()) {
    fprintf(stderr, "ERROR: could not start GLFW3n");
    return 1;
  }
  // uncomment these lines if on Apple OS X
  /*glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
  glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);
  glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
  glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);*/
  GLFWwindow* window = glfwCreateWindow(640, 480, "Hello Triangle", NULL, NULL);
  if (!window) {
    fprintf(stderr, "ERROR: could not open window with GLFW3n");
    glfwTerminate();
    return 1;
  }
  glfwMakeContextCurrent(window);
  // start GLEW extension handler
  glewExperimental = GL_TRUE;
  glewInit();
  // get version info
  const GLubyte* renderer = glGetString(GL_RENDERER); // get renderer string
  const GLubyte* version = glGetString(GL_VERSION); // version as a string
  printf("Renderer: %sn", renderer);
  printf("OpenGL version supported %sn", version);
  // tell GL to only draw onto a pixel if the shape is closer to the viewer
  glEnable(GL_DEPTH_TEST); // enable depth-testing
  glDepthFunc(GL_LESS); // depth-testing interprets a smaller value as "closer"
  /* OTHER STUFF GOES HERE NEXT */
  // close GL context and any other GLFW resources
  glfwTerminate();
  return 0;
}

我使用了CodeBlocks。在"include"文件夹中,我有这些文件的目录(GL/GLFW)。如您所见,它们#include在代码的顶部。

但是,这会返回一个"未定义引用"错误的长列表。我曾见过有人提到链接器,并提供了一长串代码,却没有解释把它们放在哪里。我不知道链接器是什么,或者更确切地说,我不知道我必须写什么代码,或者把它放在哪里才能使它工作。

请给予明确的解释和实际的帮助。

将c++源代码转换为可执行程序的过程包括多个步骤:

  • 预处理
  • 编译
  • 组装

但是,通常您只运行g++,然后运行不同的程序,每个程序执行一个步骤。这就是为什么你可以在g++的命令行中指定链接器的参数,它们只会在链接器上传递。

所以,对于你的问题:你需要链接包含你想要使用的符号(函数,方法等)的库。在不看到错误消息的情况下,判断哪些库及其位置是不同的。但是,由于您包含GL头文件,您很可能需要链接libgl…

链接器参数是-L指定库所在的位置(=目录),-L指定要链接的库。库名中的'lib'以及库文件后缀(。因此,a)可以省略,例如-lpthread链接库libpthread.so.