SDL2和CMake在OS X 10.11上运行

SDL2 and CMake on OS X 10.11

本文关键字:运行 OS CMake SDL2      更新时间:2023-10-16

我知道有一些答案(例如这里、这里或这里),但我无法让它发挥作用:

考虑MWEmain.cpp

// depending on the source of the example,
// one of the two includes is used
//#include <SDL2/SDL.h>
#include "SDL.h"
int main() {
    //Start SDL
    SDL_Init( SDL_INIT_EVERYTHING );
    //Quit SDL
    SDL_Quit();
    return 0;
}

我在OS X 10.11上下载了SDL2 v2.0.4,并将SDL2.framework文件复制到/Library/Frameworks文件夹中。

现在,我正试图找到一个有效的CMake脚本来编译main.cpp.

首先我尝试了

find_package(SDL)
add_executable(example main.cpp)
target_include_directories(example ${SDL_INCLUDE_DIR})
target_link_libraries(example ${SDL_LIBRARY})

但我收到错误信息

Could NOT find SDL (missing:  SDL_LIBRARY) (found version "2.0.4")
CMake Error at CMakeLists.txt:3 (target_include_directories):
  target_include_directories called with invalid arguments

如果我将FindSDL2.cmake包含在cmake子目录中,并使用脚本

set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${PROJECT_SOURCE_DIR}/cmake")
find_package(SDL2 REQUIRED)
include_directories(${SDL2_INCLUDE_DIR})
add_executable(example main.cpp)

CMake工作,但我得到一个链接器错误:

Undefined symbols for architecture x86_64:
  "_SDL_Init", referenced from:
      _main in main.cpp.o
  "_SDL_Quit", referenced from:
      _main in main.cpp.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

你知道我的问题是什么吗?我如何以这种方式正确使用SDL2?

您需要为目标添加target_link_libraries(YOUR_TARGET ${SDL2_LIBRARY})——它不是针对sdl链接的。

如果运行make VERBOSE=1,您可以看到实际的链接。