0

My project folder looks as follows:

foo/                --> Project name
  CMakeLists.txt
  build/            --> Run cmake.. and make.
  src/
    app.h
    app.cc
    main.cc
  share/
    foo/
      config.txt

I want my C++ code to be able to find config.txt when I do a make build and also when I do a make install.

I tried using a relative path to read config.txt as follows:

const std::string CONFIG_FILE_PATH = "../share/foo/config.txt";

But I realize this runs relative to the folder from where I run the binary, not relative to where the binary is currently located.

What I want is the path to be as follows:

// make build
const std::string CONFIG_FILE_PATH = "/home/myuser/foo/share/foo/config.txt";

// make install
const std::string CONFIG_FILE_PATH = "/usr/share/foo/config.txt";

Is there some sorcery I can do to achieve this? I'm certain this has been done before, but I don't know what to search for.

Plasty Grove
  • 2,807
  • 5
  • 31
  • 42
  • If you want from the executable obtain a directory where this executable resides, then see that question: https://stackoverflow.com/questions/1023306/finding-current-executables-path-without-proc-self-exe. By knowing the executable's directory, you may compute the path to its config file. – Tsyvarev Mar 17 '20 at 14:30
  • @Tsyvarev - Thanks for sharing that link. Wow that's complicated! Is this how all applications do it? If it were that complex, why did Linux choose to use this format of having binaries go to `/usr/bin` and configs go to `/usr/share` instead of just have a single project folder? Seems very strange to me. – Plasty Grove Mar 17 '20 at 14:46
  • With a single project's folder you would use path ` + "/config.txt"`, with having binaries under `/usr/bin` and configs under `/usr/share` you would use path ` + "/../share/config.txt"` - not a much difference. If you don't wont to compute an executable directory (``) at *runtime*, then you may use **absolute path** to the config file. This would make your build tree unusable, but who cares... Alternatively, you may read a path from some **environment variable** and fallback to the absolute path only if environment variable is not set. – Tsyvarev Mar 17 '20 at 15:33
  • Actually, there are a lot of approaches for tell path to the config file to the executable. And CMake is mostly **unrelated** to that problem, except you may use `add_compile_definitions` for define a macro when build the executable. – Tsyvarev Mar 17 '20 at 15:36
  • @Tsyvarev - Thanks for your suggestions! I guess I will go with `readlink /proc/self/exe` as per the link in your first post. Could you please put the comments above as an answer and I will accept yours? – Plasty Grove Mar 18 '20 at 12:54

0 Answers0