C # preprocessor distinguishes between operating systems
Sorry, you can't. And this is even logical: if you compile for AnyCPU
, then your program runs on any platform.
What you can do is create multiple project configurations where #define
you want to set (in project properties, Build, compilation conditionals).
But maybe it's an XY problem ... Usually you don't need to do this and you can live with
if (Environment.OSVersion.Platform == PlatformID.Win32NT)
{
}
else if (Environment.OSVersion.Platform == PlatformID.MacOSX)
{
}
else if (Environment.OSVersion.Platform == PlatformID.Unix)
{
}
source to share
What you are asking is possible, but it takes a little work.
-
Define a preprocessor variable in
csproj
<PropertyGroup Condition=" '$(OS)' == 'Windows_NT' "> <DefineConstants>_WINDOWS</DefineConstants> </PropertyGroup>
-
Use this in your code
#if _WINDOWS // your windows stuff #else // your *nix stuff #endif
I find this method useful when you have OS-specific constants (like native library names)
source to share
No - think about it, the compiler works once, but the same binary output can be used on multiple machines.
Now you can specify whatever symbols you want when compiling, so that you can easily compile three different times and pass different preprocessor symbols each time.
If you don't need any compile time changes, you can simply use Environment.OSVersion
to determine the operating system you are running under.
source to share