问题
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