c++include-path

Given two absolute paths A and B, how to get the relative path from A to B


I have a programm which generates a header and a source file, both can be stored in different directionaries from each other. I want to have the header file as an include in the source file, here is my problem how can I construct the include such that it's working even if they are in completly different dirs?

E.g. source path: C:/AA/BB/EE/source.cpp , header path: C:/AA/CC/DD/header.h => #include "../../CC/DD/header.h (No absolut paths in the include, no use of third party libraries).

My current idea is that I split both paths between the slashes, put them into an array and compare them, but I can't figure out the rest.


Solution

  • You can use std::filesystem::relative:

    #include <iostream>
    #include <filesystem>
    
    int main() {
        auto p = std::filesystem::relative("a/b/c/d","a/b/x/y");
        std::cout << p;
    }
    

    Output:

    "../../c/d"