问题
I am trying to compile some C++ source file with MSVC2008 compiler from Java code. E.g. i have a path to the source file and the path to ms compiler. I need to run compiler and get the executable file path or an error status. But everything i get so far is "No include paths defined" error and the exit status of 2
.
Googling a bit gave me the vsvars32.bat
file path which fixed this error when running from a raw cmd
. But it seems that Java has its own environment, totally different from the OS one when running a process with ProcessBuilder
.
So far i've got this code:
compilerPath = String.format("\"C:\\Program Files (x86)\\Microsoft Visual Studio 9.0\\VC\\bin\\cl.exe\" \"%s\"", sourcePath);
ProcessBuilder builder = new ProcessBuilder(compilerPath);
Process process = builder.start();
builder.redirectErrorStream(true);
process.waitFor();
This returns exitValue == 2
and the error mentioned above any time i run it.
How this can be fixed so i can just run cl.exe
and get my executable?
回答1:
You can just run cl.exe
if it is just in your PATH. It is not a java question. It is the configuration of your OS.
The problem is that probably you cannot configure environment of every machine where you are running your application. And other possible problem is that probably the compiler must be executed in specific directory (e.g. in the project directory).
Obviously the spaces in path add yet another level of complexity.
First try to do exactly the same from command prompt. There is a chance that it will fail too and will print the reason.
If it works return to your java code but try to read the STOUT and STDERR of cl.exe
. I believe it prints something that can help you to understand what's the problem.
回答2:
The trick was to set INCLUDE
and LIB
environment variables for the ProcessBuilder
and its Process
'es:
ProcessBuilder builder = new ProcessBuilder("cl.exe main.cpp /nologo".split("\\s+"));
builder.redirectErrorStream(true);
builder.environment().put("INCLUDE", "C:\\Program Files (x86)\\Microsoft Visual Studio 9.0\\VC\\include;C:\\Program Files (x86)\\Microsoft SDKs\\Windows\\v7.0A\\Include");
builder.environment().put("LIB", "C:\\Program Files (x86)\\Microsoft Visual Studio 9.0\\VC\\lib;C:\\Program Files (x86)\\Microsoft SDKs\\Windows\\v7.0A\\Lib");
Process process = builder.start();
process.waitFor();
来源:https://stackoverflow.com/questions/8553133/running-msvc-compiler-from-java-code-gives-error