Search code examples
c++cmd

How do I build a Visual Studio project from inside a C++ program, using system() to access command line?


I'm trying to make a Visual Studio project build/compilation from the command line, but from inside a C++ program. I can get this working if I use the command line directly and running the following:

cd C:\Program Files (x86)\My Project Folder
"C:\Program Files\Microsoft Visual Studio\2022\Community\Common7\\IDE\devenv.exe" MyProject.sln /Build Release

The trouble is that these commands are not working from inside a C++ program using system() like so:

system("cd C:\\Program Files (x86)\\My Project Folder");
system("\"C:\\Program Files\\Microsoft Visual Studio\\2022\\Community\\Common7\\IDE\\devenv.exe\" MyProject.sln /Build Release");

Can anyone help me to get these commands working from inside the C++program?


Solution

  • You need to make a couple of changes:

    1. Each system() call is new, so you will need to use && to do multiple commands
    2. You need to escape quotation marks with \" otherwise the quotations will be used to denote a string instead of being passed to cmd
    3. You need to use 2 backslashes in the path \\

    Eg.

    system("cd \"C:\\Program Files (x86)\\My Project Folder\" && \"C:\\Program Files\\Microsoft Visual Studio\\2022\\Community\\Common7\\IDE\\devenv.exe\" MyProject.sln /Build Release");
    

    I suggest using raw string literals for better readability.

    system(R"(cd "C:\Program Files (x86)\My Project Folder" && "C:\Program Files\Microsoft Visual Studio\2022\Community\Common7\IDE\devenv.exe" MyProject.sln /Build Release)");