如何编写一个通过从shell运行来编译自己的程序?
发布时间:2020-12-15 22:03:43 所属栏目:安全 来源:网络整理
导读:我经常想在c中尝试一下,而不会遇到编写Makefile,创建项目或输入复杂命令行的麻烦. 我想知道是否可以创建一个也是bash脚本的.cpp文件,因此它可以编译并运行自己. 我还希望能够在脚本中指定命令行选项,以防有像boost这样的依赖项. 解决方法 为什么不制作一个脚
我经常想在c中尝试一下,而不会遇到编写Makefile,创建项目或输入复杂命令行的麻烦.
我想知道是否可以创建一个也是bash脚本的.cpp文件,因此它可以编译并运行自己. 我还希望能够在脚本中指定命令行选项,以防有像boost这样的依赖项. 解决方法
为什么不制作一个脚本来监视cpp文件(或它所在的dir)并重新编译cpp文件以进行任何新的更改,而不是制作一个也可以编译自身的cpp文件的脚本? inotifywait是为此而做的.虽然这并不能完全满足您的问题要求,但它会使您的代码无法承载所有脚本行李.例:
.cpp文件 #include <iostream> using namespace std; int main (void) { cout << endl << "Code Running (ver. 10)" << endl << "and being timed." << endl; return 0; } inotifywait脚本 #!/bin/bash # watchdir=${1:-$PWD} src=${1:-app.cpp} ## set the source and output (exe) names out=${src%.cpp} while inotifywait -q -e modify -e modify -e close_write -e delete "$PWD"; do printf "n compiling 'g++ %s -o %s'nn" $src $out [ -f $out ] && rm $out ## remove existing exe before building g++ -o $out $src ## build new exe [ -f $out ] || { ## validate new exe created printf "error: compilation failed. exiting script.nn" printf "usage: %s source.cpp (default: app.cpp)nn" exit 1 } [ -x $out ] || { ## validate it is executable printf "error: file produced from compilation is not executable.n" exit 1 } time ./$out 2>&1 ## compute elapsed time exesz=$(du -h $out | awk '{print $1}') ## store disk usage (removing name) ## print results printf "n Source file: %sn" "$src" printf " output file: %sn" "$out" printf " size of exe: %s bytesnn" "$exesz" done 您可以在前台或后台运行脚本.例如.: 示例(app.cpp上的输出保存) $./watch.sh /home/david/scr/tmp/stack/dat/tmp/bld/ MODIFY app.cpp compiling 'g++ app.cpp -o app' Code Running (ver. 10) and being timed. real 0m0.003s user 0m0.001s sys 0m0.001s Source file: app.cpp output file: app size of exe: 16K bytes (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容