C # preprocessor distinguishes between operating systems

Is it possible to distinguish between operating systems in C#

using preprocessor

? eg:

#if OS_WINDOWS
//windows methods
#elif OS_MAC
//mac  methods
#elif OS_LINUX
//linux methods
#endif

      

+3


source to share


3 answers


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)
{

}

      

+4


source


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)

+3


source


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.

0


source







All Articles