0

Using Visual Studio 2019 and C#. I know of two ways to define conditional compilation symbols in a C# project.

Option 1: At top of the .cs file, applying to that .cs file only
#define SymbolThisFileOnly

Option 2: Applies to all .cs files across the entire project
Project > Properties > Build > Conditional compilation symbols > SymbolThisProjectOnly

All good so far. Now I'd like to define a symbol, ideally in one place, that applies across two or more projects. Both projects are part of a larger solution.

Usage example:

Project 1 (DLL): Gather some diagnostics in DEBUG mode
#if DEBUG && DbgCountRecordsRead
// ... code to gather some diagnostics in project 1 (DLL)
#endif

Project 2 (main EXE): Show something when the user clicks a button
#if DEBUG && DbgCountRecordsRead
// ... code to display diagnostics in project 2 (EXE)
#endif

The DEBUG guards are to prevent code accidentally being included in RELEASE builds.

Is this possible (either in C# or as a feature of Visual Studio)? The symbol(s) could be defined twice, but this is error-prone.

UPDATE

The question linked to in the top comment by @GTHvidsten provided a few suggestions, but I have not been able to get them to work. Specifically, I place a file called Directory.Build.props in the root of my git repo (and only there for some reason), with the following contents:

<Project>
    <PropertyGroup>
        <DefineConstants>TEST_SYMBOL_1</DefineConstants>
    </PropertyGroup>
</Project>

Then close and re-open Visual Studio (there is a bug, still to be addressed, in VS2019 and VS2022 that requires this). When I recompile the C# projects, the symbol is NOT recognised.

Anybody know the specifics of how to get the solution-wide conditional compilation symbols in Directory.Build.props working?

AlainD
  • 5,413
  • 6
  • 45
  • 99
  • 2
    There are a couple of answers in this question that might work. Have you tried these? (`Directory.Build.props` or `SolutionDefines.targets`) https://stackoverflow.com/questions/5149351/solution-wide-define – TheHvidsten May 22 '23 at 10:23
  • @GTHvidsten: Thanks. Didn't spot that question. Looks like there are some techniques that work on recent versions of `Visual Studio`. Will try them out, and see which option works best (then direct back to that question). – AlainD May 22 '23 at 10:32
  • Hello, [C# Propagate Conditional Compilation Symbols to multiple projects](https://stackoverflow.com/questions/51092340/c-sharp-propagate-conditional-compilation-symbols-to-multiple-projects) gave some ideas. For example, msbuild defines conditional compilation symbols or converts different configurations in web.config – wenbingeng-MSFT May 23 '23 at 09:32

0 Answers0