Visual Studio Doesn't Recognize Header Map

If you’re here it’s likely you’ve made the dumb mistake of using header maps in Xcode and then attempting to compile on windows in visual studio, only to realize your entire project is absolutely f**cked up.

Here’s a python script to help you.

drop this in your project root and set the relative path in the directories array to all your source folders which need correction. Then run this, it will scan .cpp & .h files and correct their header includes to relative paths.

import os
import shutil
import in_place

# REPLACE THESE PATHS WITH PATHS TO YOUR SOURCE FILES
directories = [
    "../../Lib1",
    "../../Lib2",
    "../../XXX/XXX/OtherSource",
    "../../XXX/XXX/Source"
]

header_map = {}
headers = []

for directory in directories:
    for root, dirs, files in os.walk(directory, topdown=False):
        for name in files:
            if name.endswith(".h") or name.endswith(".cpp"):
                path = os.path.join(root, name)
                header_map[name] = path
                headers.append(path)
                
                
                
for header_path in headers:
    with in_place.InPlace(header_path) as file:
        for line in file.readlines():
            if line.startswith("#include"):
                include_file = line.split(" ")[1].replace('"', "").strip()
                include_file = include_file.split("/")[-1]
                
                if "<" not in include_file.lower():
                    if include_file in header_map.keys():
                        rel_path = os.path.relpath(header_map[include_file], header_path)[3:]
                        new_line = f'#include "{rel_path}"\n'
                        print("----------")
                        print(header_path)
                        print(header_map[include_file])
                        print(new_line)
                        file.write(new_line)
                        
                    else:
                        file.write(line)
                else:
                    file.write(line)
            else:
                file.write(line)

then just python3 header_mapper.py and it will save you a lot of pain.

Of course if anyone has a better solution than this I’m all ears! Big fan of the Xcode Headermap features to avoid big gnarly include paths on complex project structures. But… alas… what a pain in the end…