Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compile C++ file Using PHP

Tags:

c++

php

cmd

I am using PHP on Windows machin. I also use Dev C++. I can perfectly compile .cpp file on CMD using this command:

g++ hello.cpp -O3 -o hello.exe

Now what I am trying to do is running the same command using php system() function, so it looks like this:

system("g++ c:\wamp\www\grader\hello.cpp -O3 -o C:\wamp\www\grader\hello.exe");

but it doesn't compile. I am lost, please tell me what am I missing?

I also looked up at this question and thats exactly what I need, but I couldnt find a usefull solution for my case there:

Php script to compile c++ file and run the executable file with input file

like image 391
Nazar Avatar asked Dec 21 '22 05:12

Nazar


1 Answers

Use the PHP exec command.

echo exec('g++ hello.cpp -O3 -o hello.exe');

should work.

There's a whole family of different exec & system commands in PHP, see here:

http://www.php.net/manual/en/ref.exec.php

If you want the output into a variable, then use :

$variable = exec('g++ hello.cpp -O3 -o hello.exe');

If that doesn't work, then make sure that g++ is available in your path, and that your logged in with sufficient enough privliges to allow it to execute.

You may find also that it's failing beacuse PHP is essentially being executed by your web server (Unless your also running PHP from the cmd prompt) , and the web server user ID may not have write access to the folder where G++ is trying to create the output file.

Temporarily granting write access to 'Everybody' on the output folder will verify if that is the case.

like image 102
shawty Avatar answered Dec 24 '22 02:12

shawty