我应该如何制作bash脚本以运行C ++程序? [英] How I should make a bash script to run a C++ program?

查看:59
本文介绍了我应该如何制作bash脚本以运行C ++程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个C ++程序,它在Linux终端中运行的命令是:

I have a C++ program and its command to run in linux terminal is:

./executable file input.txt parameter output.txt

我想为此制作一个bash脚本,但是我不能.我尝试了这个:

I want to make a bash script for it, but I cannot. I tried this one:

#!/bin/bash
file_name=$(echo $1|sed 's/\(.*\)\.cpp/\1/')
g++ -o $file_name.out $1
if [[ $? -eq 0 ]]; then
    ./$file_name.out
fi

但这是不正确的,因为它既不获取输入,也不获取数值参数.预先感谢.

but it is not right, because it does not get input and also numerical parameter. Thanks in advance.

推荐答案

此脚本假定第一个参数是源文件名,并且它是.cpp文件.为简洁起见,发布了错误处理.

This script assumes the first argument is the source file name and that it's a .cpp file. Error handling emitted for brevity.

#!/bin/bash
#set -x
CC=g++
CFLAGS=-O
input_file=$1
shift # pull off first arg
args="$*"
filename=${input_file%%.cpp}

$CC -o $filename.out $CFLAGS $input_file
rc=$?

if [[ $rc -eq 0 ]]; then
   ./$filename.out $args
   exit $?
fi

exit $rc

因此,例如,运行带有参数"myprogram.cpp input.txt参数output.txt"的脚本"doit",我们会看到:

So, for example running the script "doit" with the arguments "myprogram.cpp input.txt parameter output.txt" we see:

% bash -x ./doit myprogram.cpp input.txt parameter output.txt
+ set -x
+ CC=g++
+ CFLAGS=-O
+ input_file=myprogram.cpp
+ shift
+ args='input.txt parameter output.txt'
+ filename=myprogram
+ g++ -o myprogram.out -O myprogram.cpp
+ rc=0
+ [[ 0 -eq 0 ]]
+ ./myprogram.out input.txt parameter output.txt
+ exit 0

这篇关于我应该如何制作bash脚本以运行C ++程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆