I am using this version 22.04 of linux Ubuntu, some things can differ with other version
Download the last version on the github repository of SD2
If you want to have the last version of SDL2 you can pull the master with git:
In a terminal, create a directory where you want to download SDL, with mkdir then :
git clone https://github.com/libsdl-org/SDL.git
cd SDL
git checkout SDL2
cmake_minimum_required(VERSION 3.10)
project(StaticProject)
set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_STANDARD_REQUIRED True)
find_package(SDL2 REQUIRED)
add_executable(${PROJECT_NAME} main.cpp)
message(STATUS "SDL2 include directories: ${SDL2_INCLUDE_DIRS}")
target_include_directories(${PROJECT_NAME} PRIVATE ${SDL2_INCLUDE_DIRS})
message(STATUS "SDL2 libraries path: ${SDL2_LIBRARIES}")
target_link_libraries(${PROJECT_NAME} ${SDL2_LIBRARIES})
set(CMAKE_FIND_LIBRARY_SUFFIXES ".a")
set(BUILD_SHARED_LIBS OFF)
set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -static-libgcc -static-libstdc++ -static")
To explain more thiis config we create a project named StaticProject, we use the prrevious build of SDL2 by requiring the user to set the path of the package. Then this path allows to find the SDL2_INCLUDE_DIRS wiith all the headers. We display a message to be sure if the path is correct. In this project we simply have one file main.cpp a simple SDL App displaying a green sqaure. The more complex step step when static linking is when linking the dependencies of libSDL2.a in Ubuntu linux.
After creating this will we need an example of main.cpp to execute :
#include <SDL.h>
#include <iostream>
int main(int argc, char* argv[]) {
if (SDL_Init(SDL_INIT_VIDEO) != 0) {
std::cerr << "SDL_Init Error: " << SDL_GetError() << std::endl;
return 1;
}
SDL_Window *win = SDL_CreateWindow("Hello SDL", 100, 100, 640, 480, SDL_WINDOW_SHOWN);
if (win == nullptr) {
std::cerr << "SDL_CreateWindow Error: " << SDL_GetError() << std::endl;
SDL_Quit();
return 1;
}
SDL_Renderer *renderer = SDL_CreateRenderer(win, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
if (renderer == nullptr) {
std::cerr << "SDL_CreateRenderer Error: " << SDL_GetError() << std::endl;
SDL_DestroyWindow(win);
SDL_Quit();
return 1;
}
bool running = true;
SDL_Event event;
while (running) {
while (SDL_PollEvent(&event)) {
if (event.type == SDL_QUIT) {
running = false;
}
}
SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);
SDL_RenderClear(renderer);
SDL_Rect greenSquare = { 270, 190, 100, 100 };
SDL_SetRenderDrawColor(renderer, 0, 255, 0, 255);
SDL_RenderFillRect(renderer, &greenSquare);
SDL_RenderPresent(renderer);
}
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(win);
SDL_Quit();
return 0;
}