我正在尝试在 ubuntu 上使用 sdl 。根据此说明(https://gist.github.com/BoredBored/3187339a99f7786c25075d4d9c80fad5)我安装了sdl2,sdl图像和sdl混合器。现在我必须在构建时将它们链接起来。下面的示例我应该如何做。
g++ myProgram.cpp -o myProgram `sdl2-config --cflags --libs` -lSDL2 -lSDL2_mixer -lSDL2_image -lSDL2_ttf
Run Code Online (Sandbox Code Playgroud)
我正在使用 Cmake,但我不知道如何链接它们......
下面的代码只是为了测试 sdl 是否工作而完成。
//MAIN
#include <iostream>
#include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>
#include <SDL2/SDL_mixer.h>
#include <SDL2/SDL_ttf.h>
int main(int argc, char*args[])
{
SDL_Init(SDL_INIT_EVERYTHING);
}
Run Code Online (Sandbox Code Playgroud)
下面的 CMakeList
# Set the minimum version of CMake that can be used
# To find the cmake version run
# $ cmake --version
cmake_minimum_required(VERSION 3.5)
# Set the project name
project (sdl)
# Create a sources variable with a link to all cpp files to compile
set(SOURCES
src/main.cpp
)
# Add an executable with the above sources
add_executable(${PROJECT_NAME} ${SOURCES})
# Set the directories that should be included in the build command for this target
# when running g++ these will be included as -I/directory/path/
target_include_directories(sdl
PRIVATE
${PROJECT_SOURCE_DIR}/inc
)
Run Code Online (Sandbox Code Playgroud)
我如何在 Cmake 中链接它们?谢谢你的时间。
要在cmake中链接库(共享/静态),您可以使用target_link_libraries命令:
target_link_libraries(<target> ... <item>... ...)
Run Code Online (Sandbox Code Playgroud)
根据文档:
<target>
add_executable()
必须是由诸如或之类的命令创建的add_library()
因此,首先我们需要找到 SDL 库,为此我们将使用以下命令:
find_package(SDL2 REQUIRED)
Run Code Online (Sandbox Code Playgroud)
要使其包含目录可供您使用,请使用以下命令:
include_directories(${SDL2_INCLUDE_DIRS})
Run Code Online (Sandbox Code Playgroud)
最后要链接 SDL2,您需要执行以下操作:
target_link_libraries(${PROJECT_NAME} ${SDL2_LIBRARIES})
Run Code Online (Sandbox Code Playgroud)
或者:
target_link_libraries(${PROJECT_NAME} PRIVATE SDL2::SDL2)
Run Code Online (Sandbox Code Playgroud)
PRIVATE
, 表示在其实现中${PROJECT_NAME}
使用SDL2
,但SDL2
不在${PROJECT_NAME}
的公共 API 的任何部分中使用。更多这里
这${PROJECT_NAME}
是<target>
,后面的所有内容都是库的名称。
# Set the minimum version of CMake that can be used
# To find the cmake version run
# $ cmake --version
cmake_minimum_required(VERSION 3.5)
# Set the project name
project (sdl)
find_package(SDL2 REQUIRED)
# Create a sources variable with a link to all cpp files to compile
set(SOURCES
src/main.cpp
)
# Add an executable with the above sources
add_executable(${PROJECT_NAME} ${SOURCES})
target_link_libraries(sdl ${SDL2_LIBRARIES})
# Set the directories that should be included in the build command for this target
include_directories(SDL2Test ${SDL2_INCLUDE_DIRS})
Run Code Online (Sandbox Code Playgroud)
参考文献: