Search code examples
c#visual-studioconditional-statementsattributesconditional-compilation

In Visual Studio 2022, is there a way to output two executables from a single project


I'm using Microsoft Visual Studio 2022 Community edition.

I want to create two executables from the same project using conditional attributes.

Example:

using System;

public class MyClass 
{
    static void Main() 
    {
#if (PROGRAM1)
        Console.WriteLine("Program 1 exclusive");
#endif
        Console.WriteLine("Common part");
#if (PROGRAM2)
        Console.WriteLine("Program 2 exclusive");
#endif
    }
}

I don't want to define PROGRAM1 or PROGRAM2 in the code, but they should be defined when I click build solution.

Also if there's a way to do more stuff like output each executable to a different directory, I would be interested.

Why I want to do this is my current code check a boolean value on the command line at start and act slightly differently depending on that value. I would prefer to have two executables with slightly different code, but that doesn't have to check this boolean.

PS: I took a look at this answer first but it doesn't really answer my question https://stackoverflow.com/questions/975355/how-to-do-ifdef-in-c-sharp


Solution

  • You can output multiple executables from a single build and you can save them to different folders and give them different file names. You can create extra configuration in addition to Debug and Release configurations that get created automatically for most projects. For each configuration you can set a different value of variables (in your case, PROGRAM1 or PROGRAM2). Once you create your configurations and set appropriate values of your variables for each configuration, you can build multiple configurations with one build command by using Batch Build feature of the Visual Studio.

    Create a build configuration

    To create a build configuration for a project:

    1. Use menu Build > Configuration Manager to open the Configuration Manager dialog box.
    2. Select a project in the Project column.
    3. In the Configuration drop-down list for that project, choose New.
    4. The New Project Configuration dialog box opens.
    5. In the Name box, enter a name for the new configuration.
    6. To use the property settings from an existing project configuration, in the Copy settings from drop-down list, choose a configuration (select Release). You can customize the settings later in the project property pages.

    Build Multiple Configurations

    To access Batch Build dialog, use the menu bar, Build > Batch Build.

    Save Outputs to Different Folders

    To output your executables to different folder and file names, you can set the OutputPath or OutputDir variables for each configuration.

    More details on build configurations is on Visual Studio Site