简体   繁体   中英

Changing Conditional Compilation in project reference in Visual Studio

I have a class library A that is used in other projects in my solution like B and C.

Class library A behaves differently based on the presence of a pre-processor directive, for example :

#if some_directive
      // some code
#else
      // some other code
#end

How can I use class library A in project B with enabled some_directive but use in project C with disabled some_directive ?

You can do something like this using the ConditionalAttribute

This is how Debug.WriteLine() is present or non-present depending on presence of the "DEBUG" symbol.

You will be able to define your own name for the conditional symbol that you use to control the presence or absence of the code.

You can then put that symbol into the list in the "Conditional compilation symbols" settings on the project properties "Build" tab for the project where you want the code.

This doesn't allow you to have the "some other code" part unfortunately, and also it only applies to entire methods.

It seems that currently this feature is not supported. According to this post :

The language doesn't support the notion of references via preprocessor macros. What you can do is use a msbuild file and alter the set of references added based on msbuild parameters.

Another workaround which I used was using solution configuration in "Configuration Manager". I created two configurations for building each projects B or C which preprocessor directive is enabled in only one of these configurations.

I Know this topic is old - for me the following approach works nicely and might fit as well: comments of (dis)advantages of this approach are welcome. If you add your .cs-file as existing Item as a link to each project - you can compile it with different directives For adding an existing item as a linked file see screenshots at this post Use folders to organize linked files.

// file ClassA.cs

namespace HelperClasses
{
     public ClassA
    {
    #if some_directive
      // some code
    #else
      // some other code
    #end
    // ....
    }
}

// using statement in Project B and C
using HelperClasses
// Add ClassA.cs in both Projects B and C
// as exiting, linked File -- not as a Reference
// set the compiler-Directives according your needs

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM