In this short postscript we’ll learn how to make use of
properly resolve the path to our resource directory where we’ll be storing all the assets needed for each lesson.
This approach lets us avoid issues with relative paths since it doesn’t depend on where the program working
directory is set when it’s run. This functionality was introduced in SDL 2.0.1 so if you haven’t updated to the latest SDL
be sure to grab that before getting started.
SDL_GetBasePath will return the path to the directory where the application executable is, so to properly find the resource
directory we’ll have to know how to change this path to get the resource directory path. For the lessons I’ll be using
the directory structure below, if you’re using a different directory structure you’ll likely need to make some
modifications to how the resource path is set.
We’ll now write a convenient utility header containing the
getResourcePath function which will be used to resolve
the resource path based on the folder structure above. The function will also take a subdirectory name to be
appended to the path so we can then get the Lesson1 resource directory with
getResourcePath("Lesson1"). The code
below is placed into the shared include directory and named res_path.h in my code. The comments throughout the code
provide more detail on what’s going on so be sure to read through them.
With our new utility function we can easily construct the resource path for our programs and no longer need to rely
on relative paths and the various hassles that come with them. To get access to this new header in our shared include
directory we’ll need to add the directory
include to our include path.
-Iflag to add the directory to your include path, eg.
We’ll now write a simple program that will print out the resource directory path to make sure everything is working correctly.
You’ll want to double check that the path output by the test program is correct as we’ll be using
throughout the lessons to reliably find the various images and other assets we need for our programs. A related function
provided by SDL is
SDL_GetPrefPath which returns the path where your application
can write personal files (save games, etc.).
I’ll see you again soon in Lesson 1: Hello World!