如何在源文件(.cpp)中包括SDL2

时间:2020-09-25 01:08:46

标签: c++ cmake sdl sdl-2

我一直试图弄清楚如何在我的库中移植SDL2。我得出的解决方案是,如果我将SDL2包含在源文件中,则不必担心include路径。我唯一需要做的就是向前声明SDL2类型。我成功地编译了代码,但是当我尝试包含未定义的函数的库错误时,下面是一个示例,对'SDL_Init'的未定义引用,有人可以向我解释我在做什么吗?错误的。

这里是一个例子:

App.h

#include <iostream>

struct SDL_Window;

class App{
   public:
     SDL_Window w;
     App(){}
     App(int width, int height)
};

App.cpp

#include "App.h"

#include <SDL.h>

App::App(int width, int height){
    SDL_Init(SDL_INIT_EVERYTHING);
    w = SDL_CreateWindow("Window", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, width, height, SDL_WINDOW_OPENGL);
}

CMakeLists.txt主页

cmake_minimum_required(VERSION 3.7)

set(PROJECT_NAME MyProject)

set(CMAKE_WINDOWS_EXPORT_ALL_SYMBOLS ON)
set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${CMAKE_SOURCE_DIR}/cmake")

Project(${PROJECT_NAME} VERSION 1.0.0)

add_subdirectory(extern/SDL2)

add_subdirectory(src)

CMakeLists.txt源代码

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

file(GLOB SDL2_HEADER_FILES "${CMAKE_SOURCE_DIR}/extern/SDL2/include/*.h")
file(GLOB_RECURSE SDL2_SOURCES "${CMAKE_SOURCE_DIR}/extern/SDL2/src/*.c" "${CMAKE_SOURCE_DIR}/extern/SDL2/src/*.cpp")

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

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

target_link_libraries(${PROJECT_NAME} PUBLIC SDL2main PUBLIC 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"
)

CMakeLists.txt测试

cmake_minimum_required(VERSION 3.7)

Project(Test)

include_directories(Test PUBLIC "${CMAKE_SOURCE_DIR}/../MyProject/include")

add_executable(Test main.cpp)

target_link_libraries(Test "${CMAKE_SOURCE_DIR}/../MyProject/lib/libMyProject.a")

0 个答案:

没有答案