【问题标题】:Why won't this OpenGL program open a window?为什么这个 OpenGL 程序不会打开一个窗口?
【发布时间】:2021-06-05 18:55:05
【问题描述】:

我目前正在尝试学习 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 从终端运行此文件时,程序会持续运行但什么也没有发生(即根本没有生成窗口),因此我必须从终端终止程序.

我在这里做错了什么,或者这对于 MacOS 上的给定代码是预期的吗?


编辑1

为了看看会发生什么,我尝试使用aforementioned guide中提供的代码:

你好.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

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


编辑2

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


EDIT3

感谢 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();
}

【问题讨论】:

  • 不,它不应该画一个正方形。我不熟悉 GLUT,但它最多只能打开一个黑色窗口。
  • @HolyBlackCat 但是我的根本没有显示任何东西(没有生成窗口)。该程序只是在没有任何东西的情况下连续运行,直到我从终端终止它。
  • @HolyBlackCat 看来你确实是对的。

标签: c++ opengl glut


【解决方案1】:

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

【讨论】:

  • 感谢您的回答。 simple.cpp 应该在哪里 glutInit(&amp;argc, argv); 去?它应该在glutCreateWindow("simple"); 之前吗?
  • ^ 是的!这样做有效(见EDIT3)!谢谢你的帮助!!
  • 我认为“在初始化之前你不能调用任何其他 GLUT 命令”会很清楚。
猜你喜欢
  • 2014-07-12
  • 2015-05-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-19
  • 2020-04-04
  • 2014-01-28
  • 2019-06-11
相关资源
最近更新 更多