0

How does one properly use file paths in source code (relative to the project root) when building with cmake?

Details: I have a cmake project with basically this layout:

project
|-src/
| |-main.c
| |-CMakeLists.c
|-dat/
| |-foo.txt
|-build/

main.c basically contains a main function that tries to open a file, specified relative to the project's root directory, i.e., dat/foo.txt. When building with cmake, the binaries are located in project/build/src, which is also the working directory when running the program. dat/foo.txt is interpreted as project/build/src/dat/foo.txt which obviously is not available. One could replace the path in the source file with ../../dat/foo.txt, which however is not at all a clean and nice solution.

This stackoverflow post states that there is no easy way for setting the working directory of code executed by cmake (furthermore, the answer refers to a solution for Visual Studio, which I am not using).

What is the best practice for this problem?

Community
  • 1
  • 1
mort
  • 12,988
  • 14
  • 52
  • 97
  • 1
    How about using [`PROJECT_SOURCE_DIR`](http://www.cmake.org/cmake/help/v3.0/variable/PROJECT_SOURCE_DIR.html) to set a preprocessor macro to the root project directory, and then use that macro inside your code? – Some programmer dude Nov 12 '14 at 10:51
  • http://stackoverflow.com/questions/25736720/export-variable-in-makefile please see a similar problem here. – Sarwan Nov 12 '14 at 11:31
  • 2
    In my experience, a good practice in this case is to copy the data to the binary directory, preferably as a custom post-build step to account for changes in the source data. This at least makes it easier to relocate the binaries without caring about anything in the source directory. – ComicSansMS Nov 13 '14 at 08:02
  • @ComicSansMS +1. We had some default config files that I always copy to the output using this method. I do this with a custom target that calls "copy_if_different" – IdeaHat Nov 13 '14 at 15:44

0 Answers0