C program compilation from a java program

2019-07-05 05:17发布

I am trying to compile a c program from a java program on Linux platform. My snippet is.

          ProcessBuilder processBuilder = new ProcessBuilder("/usr/bin/gcc",
          "-c","/hipad/UserProject/example.c");

          Process proc = processBuilder.start();

There is no error during compilation of java program but I am not able to get .o file. I tried to find out solutions but no one is working. Any suggestion.....

1条回答
Fickle 薄情
2楼-- · 2019-07-05 06:09

The default working directory of a child process is what ever directory the Java process has as a working directory, which usually is where it was launched from. And by default gcc writes output files to current working directory. That's where you should find example.o.

There are two simple ways to solve this. You can give gcc -o option and full path and name of desired output file, or you can set working directory of child process, like this:

ProcessBuilder processBuilder =
    new ProcessBuilder("/usr/bin/gcc", "-c","example.c"); // source in working dir
processBuilder.directory(new File ("/hipad/UserProject")); // or whatever
Process proc = processBuilder.start();

See ProcessBuilder javadoc for more info.

查看更多
登录 后发表回答