Search code examples
haskellsdl-2

How to setup sdl2 in haskell with no cabal? (linux)


Beginner to haskell here. (OS: WSL Debian, installed the official ghc package)

I want to setup sdl2 so that I can compile sdl2 with haskell.

When I first tried to compile with SDL2, I got this error:

$ cat sdl2_test.hs 
import SDL

main :: IO ()
main = do
...

$ ghc sdl2_test.hs -lsdl2
[1 of 2] Compiling Main             ( sdl2_test.hs, sdl2_test.o )

sdl2_test.hs:1:1: error:
    Could not find module ‘SDL’
    Use -v (or `:set -v` in ghci) to see a list of the files searched for.
  |
1 | import SDL
  | ^^^^^^^^^^

When I compile a C program that includes SDL2, it works automatically, but it didn't work in haskell.

I then learned that I needed to import a different module for SDL2 to compile with haskell, but it requires "cabal".

How can I compile a haskell file with sdl2, without using cabal?


Solution

  • Note: The following answer assumes you are using the official Debian ghc package. If you aren't, please update your question with some information on how you installed Haskell (e.g., using GHCup, or some other method).

    Anyway, if you're using the Debian ghc package for your Haskell installation, then the easiest thing to do will be to install the compatible libghc-sdl2-dev Debian package. This includes the missing SDL module and will also install all the library dependencies you need (though most should already be installed if you have libsdl2-dev installed).

    On a fresh Debian bookworm installation, I installed ghc and libghc-sdl2-dev, and then was about to start up ghci and import the SDL module:

    $ apt install ghc libghc-sdl2-dev
    ...
    $ ghci
    GHCi, version 9.0.2: https://www.haskell.org/ghc/  :? for help
    ghci> import SDL
    ghci>
    

    I also compiled a test file:

    $ cat sdl2_test.hs
    import SDL
    
    main :: IO ()
    main = initializeAll
    $ ghc sdl2_test.hs
    [1 of 1] Compiling Main               ( sdl2_test.hs, sdl2_test.o)
    Linking sdl2_test ...
    $ ./sdl2_test
    $
    

    WARNING: You should not add -lsdl2 to the ghc command line. (It'll just cause an error.) GHC will automatically link with the correct library thanks to the import SDL line in your program.