我按照本教程使用 SDL2 设置了一个非常简单的 opengl 程序。为了这个问题,我删除了部分内容。程序打开一个窗口,将背景颜色设置为红色,然后循环直到按下退出键。
#include <unistd.h>
#include <string>
#include <iostream>
#include <OpenGL/gl.h>
#include <SDL2/SDL.h>
using namespace std;
void CheckSDLError(int line = -1) {
std::string error = SDL_GetError();
if (error != "") {
std::cout << "SLD Error : " << error << std::endl;
if (line != -1) {
std::cout << "\nLine : " << line << std::endl;
}
SDL_ClearError();
}
}
bool SetOpenGLAttributes() {
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2);
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
return true;
}
SDL_Window *mainWindow;
SDL_GLContext mainContext;
bool sdlInit() {
// Initialize SDL's Video subsystem
if (SDL_Init(SDL_INIT_VIDEO) < 0) {
std::cout << "Failed to init SDL\n";
return false;
}
mainWindow = SDL_CreateWindow("SDL2 window, son", SDL_WINDOWPOS_CENTERED,
SDL_WINDOWPOS_CENTERED,
640, 640, SDL_WINDOW_OPENGL);
if (!mainWindow) {
std::cout << "Unable to create window\n";
CheckSDLError(__LINE__);
return false;
}
// Create our opengl context and attach it to our window
mainContext = SDL_GL_CreateContext(mainWindow);
SetOpenGLAttributes();
// This makes our buffer swap syncronized with the monitor's vertical refresh
SDL_GL_SetSwapInterval(1);
return true;
}
void mainLoop() {
while (true) {
usleep(40000);//40 ms = 40000 us
SDL_Event event;
while (SDL_PollEvent(&event)) {
cout << "here\n";
glClearColor(1.0, 0.0, 0.0, 1.0);
glClear(GL_COLOR_BUFFER_BIT);
SDL_GL_SwapWindow(mainWindow);
if (event.type == SDL_QUIT) {
return;
}
if (event.type == SDL_KEYDOWN) {
switch (event.key.keysym.sym) {
case SDLK_ESCAPE:
return;
break;
}
}
}
}
}
int main(int argc, char** argv) {
if (!sdlInit()) {
return -1;
}
mainLoop();
SDL_GL_DeleteContext(mainContext);
SDL_DestroyWindow(mainWindow);
SDL_Quit();
return 0;
}
当我在我的 mac 上使用 clang 编译时,该程序可以编译、链接和工作
g++ -g -std=c++0x -Wall main.cpp -o prog -framework opengl -framework SDL2
但是,如果我尝试链接Facebook 的 Folly,如下所示:
g++ -g -std=c++0x -Wall main.cpp -o prog -framework opengl -framework SDL2 -lfolly
该程序仍然可以成功编译和链接。但是,当我运行该程序时,它每次都会在几秒钟后崩溃。lldb 显示以下内容:
Process 36200 stopped
* thread #4: tid = 0xf254f, 0x00007fff9c6891f4 libsystem_platform.dylib`OSSpinLockLock + 7, stop reason = EXC_BAD_ACCESS (code=1, address=0x390)
frame #0: 0x00007fff9c6891f4 libsystem_platform.dylib`OSSpinLockLock + 7
libsystem_platform.dylib`OSSpinLockLock:
-> 0x7fff9c6891f4 <+7>: lock
0x7fff9c6891f5 <+8>: cmpxchgl %ecx, (%rdi)
0x7fff9c6891f8 <+11>: je 0x7fff9c6891ff ; <+18>
0x7fff9c6891fa <+13>: jmp 0x7fff9c689d6e ; _OSSpinLockLockSlow
我的模糊理解是 SDL2 是动态链接的,在阅读了这个答案之后,我假设当我链接愚蠢时,我使用的某些库的实现与我不链接愚蠢时不同。我也不确定它是否相关,但我能够编译上面的代码并链接到我的 Ubuntu 桌面上的愚蠢,并且生成的二进制文件可以毫无问题地运行。为了在 Mac 10.11.5 上同时使用 SDL2 和愚蠢,我需要做什么?