Wednesday, February 20, 2013

How to make a c++ file executable like a script

I was wondering if a c++ file could be compiled and executed like could be a shell script interpreted by adding #!/bin/<shell> at first.
So i tried some ways and i found an almost satisfying one.
just by adding the following line at the beginning of a c++ file (don't forget a chmod +x on it).

//usr/bin/g++ -O3 $0 -o /tmp/$0.$$ && /tmp/$0.$$ $* ;rm /tmp/$0.$$;exit

So here is a test.cxx example :
----------------------------------------- CUT HERE ---------------------------------------------
//usr/bin/g++ -O3 $0 -o /tmp/$0.$$ && /tmp/$0.$$ $* ;rm /tmp/$0.$$;exit

#include <iostream>

int main(int argc, char** argv) 

{
  std::cerr << "run" << std::endl;
  return 0;
}

----------------------------------------- CUT HERE ---------------------------------------------

Tested with tcsh, ksh, csh and bash under linux :
> ./test.cxx
run
> ksh ./test.cxx
run
> bash ./test.cxx
run
> csh ./test.cxx
run
> tcsh ./test.cxx
run
> zsh ./test.cxx
run

Whoa this works well !

this is more simplier than the solution proposed here :
http://llg.cubic.org/tools/c++int/
 Which is the same idea but a more complicated way.

We could use the same idea of environment variable like this :
on bash for example:
export SCXX=g++
export SCXXFLAGS=-O3

then change the first line of your c++ file:
//`which $SCXX` $SCXXFLAGS $0 -o /tmp/$0.$$ && /tmp/$0.$$ $* ;rm /tmp/$0.$$;exit

Testing again :
> ./test.cxx
run
> ksh ./test.cxx
run
> bash ./test.cxx
run
> csh ./test.cxx
run
> tcsh ./test.cxx
run
> zsh ./test.cxx
run

of course it works also for a C file too.
Simple, easy and elegant. Don't you think ?

Have fun folks.