Issue
I am creating some software with C++ and Cmake that I want people to be able to effortlessly build and run. Cloning the GitHub repo will install the folder Project/
, and the code in the file Project/src/navigation/camera/image.cpp
compiled into and linked to multiple programs all over the Project
repository. However, inside image.cpp
there is a path to a file Project/Models/model.txt
, and the file path is relative to Project/build/navigation/camera/image.o
:
image.cpp:
int processImage() {
read_file("../../../Models/model.txt");
// Do something
}
But since the object file is linked to other programs all over the project, the path should be relative to many different locations. What is the standard "Software Engineering" technique to solve this? Do you tell Cmake the path of Project/
, and somehow let it modify image.cpp before building? Or is there a way to still use relative paths?
Solution
If you are using CMake, the typical build model separates the source tree from the build tree, which means that your build folder could be anywhere relatively to the source folder. Therefore, any relative path wouldn't work reliably.
If I can't avoid having an hardcoded path in the source, my favourite solution is to pass your cpp file to the configure
function of CMake to replace that relative path to an absolute path that CMake will calculate at generation time
Answered By - Triskeldeian