Carlos Vazquez
Carlos Vazquez

Reputation: 466

Cmake: How to refer to files within an object file that is linked to multiple programs?

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?

Upvotes: 0

Views: 237

Answers (2)

JaMiT
JaMiT

Reputation: 16843

I don't know how "standard" this approach is, but what I would expect is a requirement that Models be a subdirectory of whatever directory the executable is executed from. Usually this is wherever the executable ends up, but not necessarily. For released projects, this directory is usually (expected to be) the installation directory. There is a caveat that other functions are capable of changing the current working directory, and that would make it more difficult for your code to find model.txt. So I would also expect a requirement that the current working directory be restored before your code is run.

If you go this route, the relative path to your data file would be Models/model.txt. It would be up to each project to copy this data to the appropriate directory (or create a link from the directory to the data file). Note that each project would probably want this configuration for release anyway since you usually should not (sometimes cannot) access the parent of your install directory.

Upvotes: 0

Triskeldeian
Triskeldeian

Reputation: 628

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

Upvotes: 1

Related Questions