Name mangling on windows vs linux


I’m developing cross platform C++ library which will be used by both C++ and C# projects. I am using windows and I have managed to compile the library for windows and cross compile it for linux, so far everything worked smoothly.
The problems occur when I try to call C++ code from C# using P/Invoke. For this I need to hardcode mangled names of functions to specify entry point of .NET DllImport attribute. I have noticed that clang generates different mangled names for each platform which makes it impossible for me to hardcode the mangled name.
I don’t have a deep understanding of how compilers work so my question is: why does clang use different name mangling for windows and linux? Is it possible to have the same mangled names for windows and linux or is it defined by the OS?


The name mangling is defined by the C++ ABI of the platform you are running on. Due to historical reasons there are two common C++ ABIs, which are the Itanium ABI and Microsofts ABI. When using clang to target MSVC (usually via clang-cl), it uses Microsofts C++ ABI to stay compatible with the Microsoft ecosystem.

C++ actually provides a mechanism to disable name mangling for scenarios such as yours. Simply add extern "C" to the functions in C++ [0]. That will lead to it using C name mangling (which is usually none and supported by tooling either way) and ideal for FFI.

[0] Language linkage -