What is the best way to make data files available to my executable at runtime?

I have a project that wants to read PNGs from a /images folder. I’ve done a few different things in the past but they all depend on where the executable is called from. My most recent attempt should make this clear:

Project tree:
- build/
- images/
    - cool_image.png
- src/
    - CMakeLists.txt
    - main.c
- CMakeLists.txt
- README.md

To build and run I:

$ cd build
$ cmake ..
$ cmake --build .
$ ./src/executable
ERROR: could not find /images/cool_image.png

My recent fix to this was to add the following line to my /src/CMakeLists.txt:

file(CREATE_LINK "${PROJECT_SOURCE_DIR}/images"
        "${CMAKE_CURRENT_BINARY_DIR}/images" SYMBOLIC)

This gets part of the way but it still requires me to be in a specific directory to run, namely the /build/src directory.

In the end, this automates the previous solution I had of just manually putting symlinks into my build folders. Is there a way to make these files available to my app no matter where it’s called from?

1 Like

CMake can’t help much here itself. You can get the path to the current executable from platform-specific APIs. Once you have that, you can make sure that the resources are always at a static location relative to that binary in the build tree and the install tree. See dlsym on Unix and I can’t remember the Windows one off-hand.

Ah ok, so this is more of a thing where I would get the absolute path during install and hard code that. The location would be platform dependent. Gotcha.