Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dot net core build platform/os specific code or class files

I want to build a .net core library that will have platform specific code for doing win32 and osx calls and when compiling the library for each target os, I want to include the correct os code.

I've looked at the corefx and lots of documents and after much googling the only way I've found is to perform OS detection at runtime but that is both inefficient and tedious. In the case of corefx, they have a complex build system that seems to automagically pull in platform specific files but that relies on msbuild and more. Am I missing something?

How do I conditionally target code for a OS either at the file level or code level such as:

#if osx
// come code
#endif

Or, as per golangs way, by putting the os name in the filename such as MyClass.osx.cs for osx code and MyClass.cs for non platform stuff and the build process will take of including the correct files itself.

I'm using Visual Studio code and project.json.

(I guess in Visual studio I could define each platform target and include my own defines but I'm on osx)

Thanks in advance.

like image 858
Damien Avatar asked Sep 18 '16 11:09

Damien


People also ask

How does .NET core compile?

Compiling MSIL to Native Code At execution time, a just-in-time (JIT) compiler translates the MSIL into native code. During this compilation, code must pass a verification process that examines the MSIL and metadata to find out whether the code can be determined to be type safe.

What does dotnet build do?

The dotnet build command builds the project and its dependencies into a set of binaries. The binaries include the project's code in Intermediate Language (IL) files with a . dll extension.

What is the difference between MSBuild and dotnet build?

Description. The dotnet msbuild command allows access to a fully functional MSBuild. The command has the exact same capabilities as the existing MSBuild command-line client for SDK-style projects only. The options are all the same.


1 Answers

You could define a build definition in your project.json

"buildOptions": {
                "define": [ "PORTABLE328" ]
            }

eg:

{
    "frameworks":{
        "netstandard1.6":{
           "dependencies":{
                "NETStandard.Library":"1.6.0",
            }
        },
        ".NETPortable,Version=v4.0,Profile=Profile328":{
            "buildOptions": {
                "define": [ "PORTABLE328" ]
            },
            "frameworkAssemblies":{
                "mscorlib":"",
                "System":"",
                "System.Core":"",
                "System.Net"
            }
        }
    }
}

Now you can conditionally compile against that target:

#if !PORTABLE328
using System.Net.Http;
using System.Threading.Tasks;
// Potentially other namespaces which aren't compatible with Profile 328
#endif

Source

like image 117
cwishva Avatar answered Nov 15 '22 10:11

cwishva