Segmentation fault when including glad.h

懵懂的女人 提交于 2021-02-05 07:13:25

问题


I am following the GLFW guide to getting started but I can't seem to make it run with GLAD.

Here's my C file (prac.c)

#include <stdio.h>
#include <stdlib.h>
#include<glad/glad.h>
#include<GLFW/glfw3.h>

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

int main(void) {
  GLFWwindow* window;

  if(!glfwInit()) return -1;

  glfwSetErrorCallback(error_callback);

  glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
  glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);
  window = glfwCreateWindow(640, 480, "Hello World", NULL, NULL);
  if(!window) {
    glfwTerminate();
    return -1;
  } 

  glfwMakeContextCurrent(window);

  printf("OpenGL version: %s\n", glGetString(GL_VERSION));

  gladLoadGL();

  while(!glfwWindowShouldClose(window)) {
    glClear(GL_COLOR_BUFFER_BIT);

    glfwSwapBuffers(window);

    glfwPollEvents();
  }

  glfwDestroyWindow(window);
  glfwTerminate();
  return 0;
}

And I compile it via a Makefile which runs these commands:

gcc -Wall -lglfw -lGL -ldl -Iglad/include -o obj/glad.o -c glad/src/glad.c
gcc -Wall -lglfw -lGL -ldl -Iglad/include -o obj/prac.o -c prac.c
gcc -Wall -lglfw -lGL -ldl -Iglad/include -o prac obj/glad.o obj/prac.o

Whenever I try to run the executable, I get a segmentation fault. However, when I comment out #include<glad/glad.h> and gladLoadGL(); and build it, it does run. This leads me to believe that the segmentation fault occurs when including glad.h, but for the life of me I can't figure out why.


回答1:


You have to call initialize glad before calling any OpenGL instruction.
That means gladLoadGL() has to be done before glGetString(GL_VERSION):

glfwMakeContextCurrent(window);

gladLoadGL();

printf("OpenGL version: %s\n", glGetString(GL_VERSION));


来源:https://stackoverflow.com/questions/59960792/segmentation-fault-when-including-glad-h

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!