Skip to content

Instantly share code, notes, and snippets.

@sojastar
Created February 19, 2024 10:28
Show Gist options
  • Save sojastar/06031e83b3b02b45362d237bbd20a5f7 to your computer and use it in GitHub Desktop.
Save sojastar/06031e83b3b02b45362d237bbd20a5f7 to your computer and use it in GitHub Desktop.
Setting up a basic Haskell SDL2 application on MacOS

1. Install SDL2 with homebrew:

$> brew install sdl2

and optionally:

$> brew install sdl2_image
$> brew install sdl2_mixer
$> brew install sdl2_gfx
$> brew install sdl2_ttf

2. Create the barebone app with cabal:

$> mkdir sdl2_basic_app
$> cd sdl2_basic_app
$> cabal init -n

3. Add the SDL2 dependencies to the application:

Edit the sdl2-basic-app.cabal file. First, modify the build-depends key by adding sdl2 and linear (update the version numbers as needed):

build-depends:  base ^>=4.17.2.1,
                sdl2 >=2.5.5.0,
                linear >=1.22

Then add the extra-lib-dir key:

extra-lib-dirs: /usr/local/Cellar/sdl2/2.28.1/lib

I'm not sure the extra-lib-dirs key is absolutely necessary.

4. A Basic Program:

Edit app/Main.hs and replace it with the following code:

{-# LANGUAGE OverloadedStrings #-}
module Main where

import SDL
import Linear (V4(..))
import Control.Monad (unless)

main :: IO ()
--main = putStrLn "Hello, Haskell!"
main = do
  initializeAll
  window <- createWindow "My SDL Application" defaultWindow
  renderer <- createRenderer window (-1) defaultRenderer
  appLoop renderer
  destroyWindow window

appLoop :: Renderer -> IO ()
appLoop renderer = do
  events <- pollEvents
  let eventIsQPress event =
        case eventPayload event of
          KeyboardEvent keyboardEvent ->
            keyboardEventKeyMotion keyboardEvent == Pressed &&
            keysymKeycode (keyboardEventKeysym keyboardEvent) == KeycodeQ
          _ -> False
      qPressed = any eventIsQPress events
  rendererDrawColor renderer $= V4 0 0 255 255
  clear renderer
  present renderer
  unless qPressed (appLoop renderer)

5. Compiling:

In the terminal enter the following command (again, modify to suite your particular setup and SDL version):

$> export PKG_CONFIG_PATH=/usr/local/Cellar/sdl2/2.28.1/lib/pkgconfig

THIS IS VERY IMPORTANT!

Then compile the application:

$> cabal build sdl2-basic-app

Compilation might take some time the first time. If all goes well run the freshly compiled application with cabal run sdl2-basic-app. You should see a blue window pop up.

6. Related links:

Haskell SDL2 bindings GitHub page

Hackage Haskell SDL2 bindings package page

Hackage Haskell linear algebra package page

The StackOverflow question about PKG_CONFIG_PATH

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment