0

我从教程开始学习 Opengl,为此我使用了 GLFW 和 GLAD。我创建了这段代码来绘制一个简单的三角形:

#include <Glad/glad.h>
#include <Glfw/glfw3.h>

#include <iostream>

void error_callback(int error, const char* description) {
  std::cout << description << std::endl;
  std::cout << error << std::endl;
}

int main() {
  GLFWwindow* window;

  if (!glfwInit()) {
    std::cout << "Glfw init failed!" << std::endl;
    return -1;
  }
  glfwSetErrorCallback(error_callback);

  window = glfwCreateWindow(640, 480, "Hello World", NULL, NULL);

  if (!window) {
    glfwTerminate();
    std::cout << "Failed to load glfw window!" << std::endl;
    return -1;
  }
  glfwMakeContextCurrent(window);

  if( !gladLoadGLLoader((GLADloadproc) glfwGetProcAddress) ) {
    std::cout << "Failed to load Opengl Context!" << std::endl;
    return -1;
  }

  float positions[6] = {
    -0.5f, -0.5f,
     0.0f,  0.5f,
     0.5f, -0.5f
  };

  unsigned int buffer;
  glGenBuffers(1, &buffer);
  std::cout << "Buffer generated successfully" << std::endl;

  glBindBuffer(GL_ARRAY_BUFFER, buffer);
  glBufferData(GL_ARRAY_BUFFER, 6 * sizeof(float), positions, GL_STATIC_DRAW);

  glEnableVertexAttribArray(0);
  glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, sizeof(float) * 2, (void*)0);

  while (!glfwWindowShouldClose(window)) {

    glClear(GL_COLOR_BUFFER_BIT);

    glDrawArrays(GL_TRIANGLES, 0, 3);

    glfwSwapBuffers(window);

    glfwPollEvents();
  }

  glfwTerminate();
  return 0;
}

可执行文件是由这个 makefile 生成的:

VER = -std=c++17
DEPDIR = -IInclude
LIBDIR = -LLibraries
LIBS = -lglfw3 -lopengl32 -lglu32 -lgdi32 -luser32 -lkernel32

main: main.cpp
    g++ $(VER) -Wall main.cpp glad.c -o main $(DEPDIR) $(LIBDIR) $(LIBS)

clean:
    rm *.o main

代码编译没有任何错误,但是当我运行程序时它崩溃了。

我还注意到控制台不打印 glGenBuffers () 函数之后的消息。

我研究了与此类似的问题,但没有一个能解决问题。

Opengl的版本是1.4

4

0 回答 0