Как поставить библиотеку SDL in C++
Знаете кого-то, кто может ответить? Поделитесь ссылкой на этот вопрос по почте, через Твиттер или Facebook.
- c++
- visual-studio-code
- sdl2
-
Важное на Мете
Похожие
Подписаться на ленту
Лента вопроса
Для подписки на ленту скопируйте и вставьте эту ссылку в вашу программу для чтения RSS.
Дизайн сайта / логотип © 2023 Stack Exchange Inc; пользовательские материалы лицензированы в соответствии с CC BY-SA . rev 2023.11.15.1019
Нажимая «Принять все файлы cookie» вы соглашаетесь, что Stack Exchange может хранить файлы cookie на вашем устройстве и раскрывать информацию в соответствии с нашей Политикой в отношении файлов cookie.
How do I link SDL with Visual Studio 2019
I don’t know how to link libraries with Visual Studio 2019 (I am using Windows 10), how do I link libraries?
asked Aug 30, 2019 at 19:06
Ninetales53 Ninetales53
49 1 1 gold badge 1 1 silver badge 2 2 bronze badges
Please see stackoverflow.com/help/how-to-ask.
Aug 30, 2019 at 19:24
1 Answer 1
It is the same as in VS 2017 and VS 2022.
Project / «your project name» Properties. /
At Configuration: select All Configurations
Project / «your project name» Properties. / Configuration Properties / VC++ Directories /
At Include Directories add path to your SDL include folder
At Library Directories add path to your SDL lib folder ( lib/x86 or lib/x64 depending the active solution platform you selected in «your project name» Properties / Configuration Manager. )
Project / «your project name» Properties. / Configuration Properties / Linker / Input /
At Additional Dependencies add ( in this order ):
SDL2.lib
SDL2main.lib
Then copy all the .dll files from «your SDL folder» / lib / ( x86 or x64 ) to your Visual Studio solution debug folder ( the debug folder in the location where your .sln file is ).
In case you have solution and project in the same folder, then copy the files directly to your solution/project folder ( the folder where your .sln file is ).
Don’t forget to use #include in your code.
Also change int main() function in main.cpp with int main(int argc, char* args[]) .
How do I statically link SDL2 in Visual Studio 2022?
I’m new to linking in general, how do I link SDL2 statically without having to have DDL’s? I have seen a couple examples online, but they aren’t easy to understand and follow. also I’ve read somewhere online that you have to statically build DDL’s into lib libraries?
asked Jul 30 at 18:04
user22310580 user22310580
1 Answer 1
You will need to build SDL2 by yourself as a static library.
First, clone the SDL Repo, preferably a stable tag, latest one being 2.28.1 at the time of writing.
Then, open the SDL Solution located at /VisualC/SDL.sln .
Once the solution has opened, right click the SDL2 project (on the right tab) and select Properties:
A new window will open, change Configuration to All configurations and Platform to All Platforms :

Then, in Configuration Properties -> General , change Configuration Type from Dynamic Library (.dll) to Static library (.lib) :

Click OK to save your changes and close the window:

Now, you can set the target platform of your choice and hit Build -> Build SDL2 to build SDL2 as a static library:

Do NOT Build the entire solution, as it will build the test projects, which will fail.
You will find built .lib files in the output folder that corresponds to your target configuration:

Do note that there won’t be any DLL, as statically linking libraries using visual studio requires a .lib (and not a .dll , as those are for dynamic linking).
Now, just follow the usual installation tutorial for VS (that normally makes you dynamically link SDL2), but copy SDL2.lib , SDL2main.lib and SDL2test.lib over the ones found in the dynamic link package.
You can then remove the DLLs.
Do not that for your project to build, you will need to statically link winmm.lib , setupapi.lib , version.lib and Imm32.lib to it.
For this, open the save property window as you opened earlier, but for your project that uses SDL2, and go in Configuration Properties -> Linker -> Input and add the aforementionned filenames into Additional Dependencies .
Your project should now build, with a static SDL2 included.
Note: If you use SDL2 modules like SDL2_image, SDL2_ttf, SDL2_mixer, etc, you will need to statically build them as well, using the same method.
Установка sdl2 на основные дистрибутивы
Здравствуй, Хабр. Недавно наткнулся на новый цикл статей по sdl2, но без процедуры установки. Вроде ничего сложного, но если интересно, то давайте вместе пройдемся по граблям, которые могут нас ожидать. Я проведу установку для xcode10 на macOS 10.14.5, code::blocks на Ubuntu 18.04 и Visual Studio 2019 Windows 10. Можно, конечно, было бы использовать clion. Одна ide на всех системах, но мне по какой-то причине не нравится их продукт. Ничего личного, просто кодинг.
Для проверки я буду использовать следующий код.
#include #include const int WIDTH = 800, HEIGHT = 600; int main( int argc, char *argv[] ) < SDL_Init( SDL_INIT_EVERYTHING ); SDL_Window *window = SDL_CreateWindow( "Hello SDL World", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, WIDTH, HEIGHT, SDL_WINDOW_ALLOW_HIGHDPI ); // Check that the window was successfully created if ( NULL == window ) < // In the case that the window could not be made. std::cout SDL_Event windowEvent; while ( true ) < if ( SDL_PollEvent( &windowEvent ) ) < if ( SDL_QUIT == windowEvent.type ) < break; >> > SDL_DestroyWindow( window ); SDL_Quit( ); return EXIT_SUCCESS; >
Ubuntu
Ставим code::blocks из магазина — здесь никаких неожиданностей. Далее создаем простенький файл mian.cpp для теста.
#include int main()
Если не собираетесь компилировать из терминала, то нужно указать target в настройках проекта.

Отлично. Далее нужно установить сам sdl2. Пишем в терминале
sudo apt install libsdl2-dev -y
После установки дадим знать ide, что нужно использовать sdl2. Перейдем в в раздел «project»->«build options». Нас интересует вкладка «Linker settings». В окно «other linker options» добавим «-lSDL2».

Заменяем на наш код. Отлично, окно рисуется.

macOS
Для установки вы можете использовать установочный образ с Сайта. На данный момент последняя стабильная версия 2.0.9.
Скачиваем и копируем в каталог /Library/Frameworks. Для использования может потребоваться аутентификация.
Запускаем xcode и выбираем проект command line tool macOS. Даем имя проекту и выбираем язык C++.
Чтобы добавить поддержку sdl2, необходимо перейти в «настройки проекта»->«build phases»->«link binary with libraries» и добавить элемент. В открывшемся окне выбрать «add other»

Добавляем наш файл /Library/Frameworks/SDL2.framework и можем проверять.
В случае, если вы предпочитаете использовать brew, то помните, что он устанавливает только статические библиотеки. В таком случае нужно передать флаг -I/usr/local/include.
Все работает, поехали дальше.

Windows
Установите vs studio. Скачайте библиотеку. Распакуйте содержимое и расположите где вам больше нравится. Я очень редко использую windows, поэтому не знаю, где хранятся все остальные библиотеки.
Создаем проект с пустым cpp файлом, либо консольное приложение, как вам удобно.
Перейдите в «проект»->«свойства»->«C/C++»->«дополнительные каталоги включаемых файлов». Добавьте путь к распакованному каталогу, указав include. В моем случае вышло \\Mac\Home\Downloads\SDL2-2.0.9\include, т.к. у меня виртуальная машина.

После этого в разделе «компоновщик»->«общие»->«дополнительные каталоги библиотек» нужно указать путь к SDL2.dll, например \\Mac\Home\Downloads\SDL2-2.0.9\lib\x64.
Осталось немного, «компоновщик»->«ввод»->«дополнительные зависимости» мы дописываем то, что необходимо использовать, SDL2.lib, SDL2main.lib, SDL2test.lib. После этого необходимо собрать проект. Собрав, скопируйте файл SDL2.dll из каталога lib\x64 или lib\x32 и поместите рядом с исполняемым файлом. Теперь пробуем наш код. Еще один момент: т.к. в «дополнительные каталоги включаемых файлов» мы указали путь сразу до подключаемых заголовков, то
#include
#include

Поздравляю, мы успешно собрали приложения под основные платформы. Надеюсь, у вас не возникнет трудностей при установке.
