简体   繁体   中英

Trying compile a C Code with PHP

I have a file named gcc.exe and I have a php page... I want to use:

gcc test.c

And, if there's some compilation error, I want to show it on the php page... But I can't. What happens is: If the file is correct, it generates the .exe file, but if it's wrong, nothing happens. What I want here, again, is to show all errors.

Anyone has an idea?

Some code: 一些代码:

<?php
exec("gcc teste.c",$results);
print_r($results)
?>

Output:

*Nothing*

I tryed put gcc output on a text file: This way (on prompt): 我尝试将gcc输出放在文本文件中:这种方式(在提示符下):

gcc test.c > teste.txt

Teorically, everythings on the screen go to text file. But this was unsucessfuly!



quantumSoup: I tryed it, and... quantumSoup:我试过了,然后......

array(0) { } int(1)

Nothing... Anything more?

gcc is likely to generate error output on stderr , which it would appear exec doesn't capture in the $results array. Solutions to this are likely to be kinda platform-specific. If you're working in a unix-like environment, it would be possible to do something like gcc foo.c 2>&1 to redirect stderr to stdout. I've no clue how one might achieve that on Windows, or if analogous concepts even exist. Perhaps someone else can elaborate if your question is platform-specific.

This is supported by the fact that piping to a file didn't work either.

exec() reference

string exec ( string $command [, array &$output [, int &$return_var ]] )

Try

exec('gcc test.c', $output, $return);

var_dump($output);
var_dump($return);

Use proc_open to capture stderr:

<?php
$process = proc_open('gcc test.c',
    array(
        1 => array("pipe", "w"),  //stdout
        2 => array("pipe", "w")   // stderr
    ), $pipes);

echo stream_get_contents($pipes[2]);

gives, for example:

sh: gcc: command not found

We use a PHP-based system that performs builds and captures results and errors under windows. We had the best success by having the PHP script create a batch file containing all the build commands, and then exec -ing that batch file. When it creates the batch file, it redirects the standard output of the compiler to one logfile and the standard error to another ( commandname >>log.txt 2>>err.txt ). Since your output is split between two files, it also helps to have the script generate lines that echo out descriptions of what is happening (such as "Building library libsockets.dll") so that you can better match up the two logs. Sometimes, it even helps to echo out every command before it is executed. Usually your build process will halt when an error is encountered (at least it probably should ), so the contents of the error log typically match up with the tail end of the normal log.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM