下载安装SDL2:
- 安装国内镜像的Homebrew,一路往下YES就行
$ /bin/zsh -c "$(curl -fsSL https://gitee.com/cunkai/HomebrewCN/raw/master/Homebrew.sh)"
- 安装sdl2
$ brew install sdl2_mixer
- 查看下sdl2库安装情况
$ brew info sdl2
根据安装的版本不同,可能得到不同的信息,下面是我的
sdl2: stable 2.0.16 (bottled), HEAD
Low-level access to audio, keyboard, mouse, joystick, and graphics
https://www.libsdl.org/
/usr/local/Cellar/sdl2/2.0.16 (91 files, 5.4MB) *
Poured from bottle on 2021-08-27 at 05:51:01
From: https://mirrors.ustc.edu.cn/homebrew-core.git/Formula/sdl2.rb
License: Zlib
==> Options
--HEAD
Install HEAD version
==> Analytics
install: 107,393 (30 days), 219,217 (90 days), 957,010 (365 days)
install-on-request: 10,041 (30 days), 19,802 (90 days), 91,778 (365 days)
build-error: 0 (30 days)
其中,第4行的/usr/local/Cellar/sdl2/2.0.16
很有用,是我们安装sdl2库的位置,下面会用到。
创建Clion项目:
我们分C项目和CPP项目。
创建项目的时候,记得选C Executable
或者C++ Executable
哦。
C项目
- CMakeLists.txt内容
cmake_minimum_required(VERSION 3.20)
project(SimpleWindow C)
set(CMAKE_C_STANDARD 11)
set(SDL_DIR /usr/local/Cellar/sdl2/2.0.16/)
include_directories(${SDL_DIR}/include/)
link_directories(${SDL_DIR}/lib/)
add_executable(SimpleWindow main.c)
target_link_libraries(SimpleWindow SDL2 SLD2_test SDL2main)
- main.c内容
#include "stdio.h"
#include <SDL2/SDL.h>
const int WIDTH = 400, HEIGHT = 400;
int main() {
if (SDL_Init(SDL_INIT_EVERYTHING)) {
printf("Can not init video");
return 1;
}
SDL_Window *win = SDL_CreateWindow(
"Hello world",
SDL_WINDOWPOS_CENTERED,
SDL_WINDOWPOS_CENTERED, WIDTH, HEIGHT,
SDL_WINDOW_ALLOW_HIGHDPI
);
if (win == NULL) {
printf("Can not create window");
return 1;
}
SDL_Event windowEvent;
while(1) {
if (SDL_PollEvent(&windowEvent)) {
if (SDL_QUIT == windowEvent.type) {
printf("SDL quit!!");
break;
}
}
}
SDL_DestroyWindow(win);
SDL_Quit();
return 0;
}
CPP项目
- CMakeLists.txt内容
cmake_minimum_required(VERSION 3.20)
project(SimpleWindow)
set(CMAKE_C_STANDARD 11)
set(SDL_DIR /usr/local/Cellar/sdl2/2.0.16/)
include_directories(${SDL_DIR}/include/)
link_directories(${SDL_DIR}/lib/)
add_executable(SimpleWindow main.cpp)
link_libraries(SDL2)
target_link_libraries(SimpleWindow SDL2 SDL2main)
- main.cpp内容
#include <iostream>
#include <SDL2/SDL.h>
using namespace std;
const int WIDTH = 400, HEIGHT = 400;
int main() {
if (SDL_Init(SDL_INIT_EVERYTHING)) {
cout << "SDL could not initialized with error: " << SDL_GetError() << endl;
return 1;
}
SDL_Window *win = SDL_CreateWindow(
"Hello world",
SDL_WINDOWPOS_CENTERED,
SDL_WINDOWPOS_CENTERED, WIDTH, HEIGHT,
SDL_WINDOW_ALLOW_HIGHDPI
);
if (win == NULL) {
cout << "SDL could not create window with error: " << SDL_GetError() << endl;
return 1;
}
SDL_Event windowEvent;
while(true) {
if (SDL_PollEvent(&windowEvent)) {
if (SDL_QUIT == windowEvent.type) {
cout << "SDL quit!!" << endl;
break;
}
}
}
SDL_DestroyWindow(win);
SDL_Quit();
return 0;
}
感谢大神:实在是牛掰