-1

I am trying to compile a project using the system keyword in my console application to call MSBuild. MSBuild spits out a project not found error, and I have no clue why. The path and project name are both correct and printed out. https://gyazo.com/624847f060e242ad702f16174ac75701

My code:

bool MSBuild::compile(std::string path, std::string solution) {
if (path.length() == 0 || solution.length() == 0)
    return false;

std::string cmd1 = "cd ";
cmd1.append(path);

std::cout << "Command: " << cmd1 << std::endl;

std::string cmd2 = "msbuild ";
cmd2.append(solution);
cmd2.append(" /p:configuration=debug");

std::cout << "Command: " << cmd2 << std::endl;

system(cmd1.c_str());
system(cmd2.c_str());
return true;
}

I have confirmed MSBuild successfully compiles the project when manually inputting the same command with the same parameters into a cmd window. https://gyazo.com/a7f4c3f07f3f44b418734f4a979ca398

1 Answers1

0

Each call to system() is spawning off a command prompt with its own environment and working (current) directory.

The second call is "unaware" of the actions of the first call, so it will be attempting to run the command you provide in whatever working directory it would use by default.

You can prove this by calling system("cd"); after your call to system(cmd1.c_str()); - it will very likely not be the value you expect!

A possible workaround would be to try to concatenate your two commands together with what the command prompt uses to chain commands, either & or && depending on your preference.

Example adapted version of your code:

bool MSBuild::compile(std::string path, std::string solution) {
if (path.length() == 0 || solution.length() == 0)
    return false;

std::string cmd1 = "cd ";
cmd1.append(path);

std::cout << "Command: " << cmd1 << std::endl;

std::string cmd2 = "msbuild ";
cmd2.append(solution);
cmd2.append(" /p:configuration=debug");

std::cout << "Command: " << cmd2 << std::endl;

std::string cmd = cmd1 + std::string(" & ") + cmd2;
std::cout << "Combined Command: " << cmd << std::endl;

//system(cmd1.c_str());
//system(cmd2.c_str());
system(cmd.c_str());
return true;
}

You'll find some related, supplementary references here in this Q&A, including the difference between & and &&: What does “&&” in this batch file?.

Another alternative would be to write your commands to a single batch file and use system() to call it.

Phil Brubaker
  • 1,257
  • 3
  • 11
  • 14