简体   繁体   English

如何在 CMake 项目中正确包含 SDL2 源代码

[英]How To Properly Include SDL2 Source Code in Project CMake

I am confused on how to statically include the source code of SDL2.我对如何静态包含 SDL2 的源代码感到困惑。 I am trying to do this to make a library I am working on more portable.我试图这样做是为了使我正在开发的库更加便携。

Currently, when I try to include my library in another project it says "Cannot open include file: 'SDL2/SDL.h': No such file or directory" .目前,当我尝试将我的库包含在另一个项目中时,它说“无法打开包含文件:'SDL2/SDL.h':没有这样的文件或目录”

My Filesystem:我的文件系统:

include
--Header Files
src
--Source Files
extern
--SDL2
build

Here is an example of the file causing the error:以下是导致错误的文件示例:

#include <iostream>
#include <SDL2/SDL.h> //Error

using namespace std;

/* The code */

Here is an example of my main CMakeLists.txt:这是我的主要 CMakeLists.txt 的示例:

cmake_minimum_required(VERSION 3.7)

set(CMAKE_WINDOWS_EXPORT_ALL_SYMBOLS ON)

project(MyProject VERSION 1.0.0)

set(SDL2_SOURCE_DIR “${CMAKE_SOURCE_DIR}/extern/SDL2”)
add_subdirectory(extern/SDL2)
add_subdirectory(src)

Here is an example of my src CMakeLists.txt:这是我的 src CMakeLists.txt 的示例:

set(PROJECT_NAME MyProject)

file(GLOB HEADER_FILES "${CMAKE_SOURCE_DIR}/include/*.h")
file(GLOB SOURCES "*.cpp")

add_library(${PROJECT_NAME} ${SOURCES} ${HEADER_FILES})

target_include_directories(${PROJECT_NAME} PUBLIC "${CMAKE_SOURCE_DIR}/include")

target_link_libraries(${PROJECT_NAME} PRIVATE SDL2main SDL2-static)

set_target_properties( ${PROJECT_NAME}
    PROPERTIES
    ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/lib"
    LIBRARY_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/lib"
    RUNTIME_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/bin"
)

add_subdirectory() will process the subdirectory as a cmake porject (process the provided CMakeLists.txt for SDL). add_subdirectory() 将子目录作为 cmake 项目处理(处理为 SDL 提供的 CMakeLists.txt)。 If you read that CMakeLists.txt, you'd see that it add the include directories relative to SDL2_SOURCE_DIR, which is empty by default.如果您阅读该 CMakeLists.txt,您会看到它添加了相对于 SDL2_SOURCE_DIR 的包含目录,默认情况下该目录为空。

What I would try is to set SDL2_SOURCE_DIR to ${CMAKE_CURRENT_SOURCE_DIR}/extern/SDL2 to make the path absolute.我会尝试将 SDL2_SOURCE_DIR 设置为 ${CMAKE_CURRENT_SOURCE_DIR}/extern/SDL2 以使路径成为绝对路径。 Like that SDL include dirs will be valid everywhere in your project.就像 SDL 包含目录将在您的项目中的任何地方都有效。

You can also manually add the correct includes by using the include_directories() directive.您还可以使用 include_directories() 指令手动添加正确的包含。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM