为什么这个 OpenGL 程序不能打开 window?

Why won't this OpenGL program open a window?

我目前正在尝试学习 C++ 和 OpenGL,我将从以下代码示例开始:

simple.cpp

#define GL_SILENCE_DEPRECATION
#include <GLUT/glut.h>

void init() {
        // code to be inserted here
}

void mydisplay() {
        glClear(GL_COLOR_BUFFER_BIT);
        // need to fill in this part
        // and add in shaders
}

int main(int argc, char** argv) {
        glutCreateWindow("simple");
        init();
        glutDisplayFunc(mydisplay);
        glutMainLoop();
}

它说 here 可以使用以下命令在 MacOS 上编译此代码:

gcc -Wno-deprecated-declarations -o hello hello.c -framework GLUT -framework OpenGL -framework Carbon 

所以我按以下方式调整命令:

gcc -Wno-deprecated-declarations -o simple simple.cpp -framework GLUT -framework OpenGL -framework Carbon

这似乎有效并创建了一个名为 simple.

的可执行文件

有人告诉我这段代码应该在黑色背景上生成一个白色方块,如下所示:

然而,当我尝试使用 ./simple 从终端 运行 这个文件时,程序连续 运行s 但没有任何反应(也就是说,没有 window完全生成),所以我必须从终端终止程序。

我是不是做错了什么,或者这是 MacOS 上给定代码的预期?


编辑1

为了看看会发生什么,我尝试使用 aforementioned guide:

中提供的代码

hello.c

#include <OpenGL/gl.h>
#include <OpenGL/glu.h>
#include <GLUT/glut.h>

void display()
{
}

int main(int argc, char **argv)
{
  glutInit(&argc, argv);
  glutDisplayFunc(display);
  glutMainLoop();
}

正如指南所说,这是“一个什么都不做的简单 OpenGL 程序”。

我编译如下:

gcc -Wno-deprecated-declarations -o hello hello.c -framework GLUT -framework OpenGL -framework Carbon 

编译正常。但是,当我尝试 运行 可执行文件时,出现以下错误:

GLUT Fatal API Usage: main loop entered with no windows created.
zsh: abort      ./hello

根据此错误消息,程序已终止,因为未创建 windows。然而,正如我所说,我的 simple.cpp 程序确实 终止(我必须强行终止它),并且它 写入创建 windows。所以我猜这意味着 windows 在 simple.cpp 中创建的,但出于某种原因,它们只是没有出现在 MacOS 上?其他人可以证实这一点吗?问题可能是空白 windows 没有出现在 MacOS 上,您需要包含其他图形元素才能显示 window 吗?


编辑2

问题是我的理解是simple.cpp中的glutCreateWindow("simple");应该创建一个window标题为“simple”,所以我不明白为什么不工作。


编辑3

多亏了 derhass 的回答,我才能让它工作:

#define GL_SILENCE_DEPRECATION
#include <GLUT/glut.h>

void init() {
        // code to be inserted here
}

void mydisplay() {
        glClear(GL_COLOR_BUFFER_BIT);
        // need to fill in this part
        // and add in shaders
}

int main(int argc, char** argv) {
        glutInit(&argc, argv);
        glutCreateWindow("simple");
        init();
        glutDisplayFunc(mydisplay);
        glutMainLoop();
}

您没有将对 glutInit() 的调用包含在您的 simple.cpp 示例中。您不能在此初始化之前调用任何其他 GLUT 命令,这样做会导致未定义的行为。