How to compile and link cpp files as seperate executables in Visual Studio?

Edward Jack 21 Reputation points
2022-12-21T18:36:21.73+00:00

I am working on the exercises in Sam's teach yourself C++ book. I want to have each chapter exercises as a separate project in a solution. I am wondering if it is possible to set it up so each .cpp file gets compiled and linked as a separate executable? for example Exercise1.cpp would get compiled as Exercise1.exe and Exercise2.cpp would get compiled as Exercise2.exe. If not would I have to have each exercise as a separate project in the solution?

Developer technologies | C++
{count} votes

Accepted answer
  1. Michael Taylor 60,326 Reputation points
    2022-12-21T20:17:29.3+00:00

    VS combines all .cpp files into a single executable per project. So if you want each .cpp to be a separate executable but you still want to use VS then you'll need to create a separate project for each .cpp file.

    If you are just using VS as the editor but are fine building from the command line then you can use the command line to select the .cpp file(s) to build into a single executable. Behind the scenes this is what VS does, it just gets the list of .cpp files the project.

    A final option, but not one I recommend, is to have a single project and then include/exclude the .cpp files that you want in the binary. This is harder to manage and can be very confusing if you come back to it later but it works.

    1 person found this answer helpful.
    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. YujianYao-MSFT 4,296 Reputation points Microsoft External Staff
    2022-12-22T03:46:32.927+00:00

    Hi @Edward Jack ,

    At present, visual studio does not support this function, and usually executes the program with a solution, but VS Code can execute a single .cpp file.

    If you need to execute a single .cpp file in visual studio, I suggest you go to DC and propose that you need this functionality.

    Best regards,

    Elya


    If the answer is the right solution, please click "Accept Answer" and upvote it.If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.