我有以下C代码(为清楚起见,我知道它不是完整的代码,它应该处理事件和类似的东西):
#!/usr/bin/tcc -run -L/usr/lib/x86_64-linux-gnu -D_REENTRANT -DSDL_MAIN_HANDLED -I/usr/include/SDL2 -lSDL2 -lGL -lGLEW
#include <GL/glew.h>
#include <SDL.h>
int main(int argc, char **argv)
{
SDL_Init(SDL_INIT_VIDEO);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 4);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
SDL_Window *win = SDL_CreateWindow("Hello World!", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 640, 480, SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE);
SDL_GLContext glContext = SDL_GL_CreateContext(win);
while (1)
{
glClearColor(1, 0, 0, 1);
glClear(GL_COLOR_BUFFER_BIT);
SDL_GL_SwapWindow(win);
}
SDL_GL_DeleteContext(glContext);
SDL_DestroyWindow(win);
return 0;
}
如果我用GCC编译它(没有shebang行),并启动可执行文件,它工作正常,但我喜欢TCC的编译和运行功能的简单性及其速度。
但是,编译后的可执行文件为我提供了以下控制台输出,然后永久挂起,甚至无法用CTRL-C杀死:
libGL error: No matching fbConfigs or visuals found
libGL error: failed to load driver: swrast
我按建议here添加了SDL_MAIN_HANDLED,但这并没有改变任何内容。
任何?
答案 0 :(得分:1)
如何正确处理SDL调用的可能错误并初始化glew?
#include <stdlib.h>
#include <SDL.h>
#include <GL/glew.h>
void exit_sdl_error(const char *message) {
SDL_LogCritical(SDL_LOG_CATEGORY_ERROR, "%s failed with SDL error %s", message, SDL_GetError());
exit(EXIT_FAILURE);
}
int main() {
const Uint32 init_flags = SDL_INIT_VIDEO;
const int gl_major = 4, gl_minor = 0;
if (!SDL_WasInit(init_flags)) {
if (SDL_Init(init_flags) != 0)
exit_sdl_error("Unable to initialize SDL");
if (SDL_InitSubSystem(init_flags) != 0)
exit_sdl_error("Unable to initialize sub system of SDL");
}
if (SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, gl_major))
exit_sdl_error("Unable to set gl major version");
if (SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, gl_minor))
exit_sdl_error("Unable to set gl minor version");
if (SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE))
exit_sdl_error("Unable to set gl profile");
SDL_Window *window = SDL_CreateWindow("Hello World!", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 640, 480, SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE);
if (!window) {
SDL_QuitSubSystem(init_flags);
exit_sdl_error("Unable to create window");
}
SDL_GLContext glContext = SDL_GL_CreateContext(window);
if (!glContext) {
SDL_DestroyWindow(window);
SDL_QuitSubSystem(init_flags);
exit_sdl_error("Unable to create context");
}
glewInit();
while (1)
{
glClearColor(1, 0, 0, 1);
glClear(GL_COLOR_BUFFER_BIT);
SDL_GL_SwapWindow(window);
}
SDL_GL_DeleteContext(glContext);
SDL_DestroyWindow(window);
SDL_QuitSubSystem(init_flags);
}