开发者

Running c++ from Java problem

开发者 https://www.devze.com 2023-01-09 00:57 出处:网络
I need to compile and run a c++ program from java. I am using Process a = Runtime.getRuntime().exec (\"g++ -g function.cpp -o function\");

I need to compile and run a c++ program from java. I am using

Process a = Runtime.getRuntime().exec ("g++ -g function.cpp -o function"); Process b = Runtime.getRuntime().exec ("./function");

the proble开发者_如何学JAVAm is that the output I get from the c++ program is not correct but If I compile and run it myself in the command line it works just fine. The problem is Java and i dont know why.

Thanks a lot

Al,


There is one definite and one probable problem that I see here. The definite problem is that Runtime.exec() does not wait for the process to complete. So you will need to add

a.waitFor();

before calling b.

The possible issue is that depending on how you are invoking this application, the current working directory may not be where you think it is. So function.cpp may not exist.


Are you waiting for process A to finish before running process B?


"The output... is not correct" doesn't help anyone to diagnose your issue. You should definitely give the output you expected, and the output you saw from Java. Assuming that your program is small, you should post the source code of that too (since this is about the compilation process after all).

By the way, what happens when you navigate to the working direction of the Java program, find the function executable it generating and invoke that yourself from the command line? Is the output correct now? The answer to this will let you know whether the problem is in the compilation step or the execution step.

If it's execution, I would hazard a guess at things like the environment (envvars, PATH, etc.) but without more information it's hard to tell.

Also, as with all question that involve Processes, take a look at these common pitfalls. It looks like you're making at least one of them (the common one of not consuming output) which might lead to your program working on trivial C++ code but deadlocking on a larger codebase.

You're also not checking the output (either the return value or the stdout/stderr streams) of the compilation step at all, so you have no idea whether the compilation was successful - and if not, what (useful) error messages you got from the compiler.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号