如何编写一个c ++程序,通过从shell运行来编译自己?

Ric*_*ges 4 c++ bash shell

我经常想在c ++中尝试一下,而不用去编写Makefile,创建项目或输入复杂的命令行.

我想知道是否可以创建一个也是bash脚本的.cpp文件,因此它可以编译并运行自己.

我还希望能够在脚本中指定命令行选项,以防有像boost这样的依赖项.

Dav*_*ica 5

为什么不制作一个脚本来监视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;
}
Run Code Online (Sandbox Code Playgroud)

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'\n\n" $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.\n\n"
        printf "usage:   %s source.cpp (default: app.cpp)\n\n"
        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:  %s\n" "$src"
    printf " output file:  %s\n" "$out"
    printf " size of exe:  %s bytes\n\n" "$exesz"

done
Run Code Online (Sandbox Code Playgroud)

您可以在前台或后台运行脚本.例如:

示例(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
Run Code Online (Sandbox Code Playgroud)