So this is probably a long shot, but is there any way to run a C or C++ file as a script? I tried:
#!/usr/bin/gcc main.c -o main; ./main
int main(){ return 0; }
But it says:
./main.c:1:2: error: invalid preprocessing directive #!
So this is probably a long shot, but is there any way to run a C or C++ file as a script? I tried:
#!/usr/bin/gcc main.c -o main; ./main
int main(){ return 0; }
But it says:
./main.c:1:2: error: invalid preprocessing directive #!
The sed command takes the
.c
file and strips off the hash-bang line.2,$p
means print lines 2 to end of file;"$@"
expands to the command-line arguments to the runc script, i.e."main.c"
.sed's output is piped to gcc. Passing
-
to gcc tells it to read from stdin, and when you do that you also have to specify the source language with-x
since it has no file name to guess from.Quite a short proposal would exploit:
The "#" being a comment in shell and "#if 0" disabling code.
Then you can
chmod +x
your .cpp files and then./run.cpp
../run.cpp Hi
a.out
, so that you can have multiple binaries in the same folder.Problems:
You might want to checkout ryanmjacobs/c which was designed for this in mind. It acts as a wrapper around your favorite compiler.
The nice thing about using
c
is that you can choose what compiler you want to use, e.g.So you get all of your favorite optimizations too! Beat that
tcc -run
!You can also add compiler flags to the shebang, as long as they are terminated with the
--
characters:c
also uses$CFLAGS
and$CPPFLAGS
if they are set as well.CINT:
Here's yet another alternative:
For C, you may have a look at tcc, the Tiny C Compiler. Running C code as a script is one of its possible uses.