Linking error in a project using SDL2

I’m currently trying Nix and nix-direnv for a small toy project in C with SDL2.

My shell.nix file looks like this:

{ pkgs ? import <nixpkgs> {} }:

with pkgs;
mkShell {
  nativeBuildInputs = [

Everything was working fine at first when I was just using the SDL2 package but when I started to include SDL2_ttf I encountered an error during the compilation:

$ make
gcc -std=c99 ./src/*.c `sdl2-config --cflags --libs` -lm -o raycast;
/nix/store/3r87a2wq1w4l66wnsm7rqvy608mx23h6-binutils-2.40/bin/ld: /tmp/ccarNoZM.o: in function `initializeWindow':
main.c:(.text+0x17): undefined reference to `TTF_Init'
collect2: error: ld returned 1 exit status
make: *** [Makefile:2: build] Error 1

In case you’re wondering, sdl2-config does find my libs correctly:

$ sdl2-config --cflags --libs
-I/nix/store/qp9jcxmnd1z3cjf2lqh88m4pr8iykzg3-SDL2-2.26.5-dev/include/SDL2 -I/nix/store/qp9jcxmnd1z3cjf2lqh88m4pr8iykzg3-SDL2-2.26.5-dev/include/SDL2 -I/nix/store/qm5i5h35lgcqxy9rsbpllrv5q0zsl4hy-SDL2_ttf-2.20.2/include/SDL2 -I/nix/store/qp9jcxmnd1z3cjf2lqh88m4pr8iykzg3-SDL2-2.26.5-dev/include/SDL2 -I/nix/store/qm5i5h35lgcqxy9rsbpllrv5q0zsl4hy-SDL2_ttf-2.20.2/include/SDL2 -I/nix/store/qp9jcxmnd1z3cjf2lqh88m4pr8iykzg3-SDL2-2.26.5-dev/include/SDL2 -I/nix/store/qm5i5h35lgcqxy9rsbpllrv5q0zsl4hy-SDL2_ttf-2.20.2/include/SDL2 -D_REENTRANT
-L/nix/store/nqgj705lic1qf8jz6x42bbhkw6dh38n1-SDL2-2.26.5/lib -Wl,-rpath,/nix/store/nqgj705lic1qf8jz6x42bbhkw6dh38n1-SDL2-2.26.5/lib -Wl,--enable-new-dtags -lSDL2

In my code I did #include <SDL2/SDL_ttf.h> correctly but the error seems to come from inside the SDL_ttf.h file when it tries to #include "SDL.h": At this point the folder contains only SDL_ttf.h so it cannot link to SDL.h.

Since I’m new to this I don’t understand if I missed something to make the two packages work together correctly. Are there any example of projects using nix-direnv and SDL2 correctly?

sdl2-config --libs only gives you the command line flags to link to SDL2, not other libraries like SDL2_ttf. Just adding -lSDL2_ttf to your command line should fix this issue. I don’t think this is particularly a Nix related issue, I think that would happen with any other development environment.

I’d recommend using pkg-config which is more generic than sdl2-config and will work for both SDL2 and SDL2_ttf:pkg-config --cflags --libs sdl2 SDL2_ttf.

1 Like