Python program Executing C++ Program Containing
Functions
Now you are going to test the Python script to
run a C++ program having functions and function calls.
Example 14.10.1 - Write a C++ program using a user
defined function to function cube of a number
/*Write a C++ program using a user defined function
to function cube of a number.*/
//Now select File→New in Notepad and type the C++ program
#include <iostream>
using namespace std;
Function declaration int cube(int num); int
main()
{
int num; int c;
cout<<"Enter any number:
"<<endl; cin>>num;
c = cube(num);
cout<<"Cube of "
<<num<< " is "<<c; return 0;
}
//Function to find cube of any number int
cube(int num)
{
return (num * num * num);
}
// Save this file as cube_file.cpp
#Now select File→New in
Notepad and type the Python program
#Save the File as fun.py
#Program that compiles and
executes a .cpp file
#Python fun.py -i
c:\pyprg\cube_file.cpp
import sys, os, getopt
def main(argv):
cpp_file = ''
exe_file = ''
opts, args = getopt.getopt(argv,
"i:",['ifile='])
for o, a in opts:
if o in ("-i", "--ifile"):
cpp_file = a + '.cpp'
exe_file = a + '.exe'
run(cpp_file, exe_file)
def run(cpp_file, exe_file):
print("Compiling " + cpp_file)
os.system('g++ ' + cpp_file + ' -o ' +
exe_file)
print("Running " + exe_file)
print("-------------------")
print
os.system(exe_file)
print
if __name__ =='__main__':
main(sys.argv[1:])
Output of the above program
Compiling c:\pyprg\cube_file.cpp
Running c:\pyprg\cube_file.exe
-------------------
Enter any number:
5
Cube of 5 is 125
Related Topics
Privacy Policy, Terms and Conditions, DMCA Policy and Compliant
Copyright © 2018-2023 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.