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 #!
Variatn of John Kugelman can be written in this way:
Since the shebang line will be passed to the compiler, and # indicates a preprocessor directive, it will choke on a #!.
What you can do is embed the makefile in the .c file (as discussed in this xkcd thread)
The
#if 0 #endif
pair surrounding the makefile ensure the preprocessor ignores that section of text, and the EOF marker marks where the make command should stop parsing input.This properly forwards the arguments and the exit code too.
I know this question is not a recent one, but I decided to throw my answer into the mix anyways. With Clang and LLVM, there is not any need to write out an intermediate file or call an external helper program/script. (apart from clang/clang++/lli)
You can just pipe the output of clang/clang++ to lli.
The above however does not let you use stdin in your c/c++ script. If bash is your shell, then you can do the following to use stdin:
As stated in a previous answer, if you use
tcc
as your compiler, you can put a shebang#!/usr/bin/tcc -run
as the first line of your source file.However, there is a small problem with that: if you want to compile that same file,
gcc
will throw anerror: invalid preprocessing directive #!
(tcc
will ignore the shebang and compile just fine).If you still need to compile with
gcc
one workaround is to use thetail
command to cut off the shebang line from the source file before piping it intogcc
:Keep in mind that all warnings and/or errors will be off by one line.
You can automate that by creating a bash script that checks whether a file begins with a shebang, something like
and use that to compile your source instead of directly invoking
gcc
.Short answer:
The trick is that your text file must be both valid C/C++ code and shell script. Remember to
exit
from the shell script before the interpreter reaches the C/C++ code, or invokeexec
magic.Run with
chmod +x main.c; ./main.c
.A shebang like
#!/usr/bin/tcc -run
isn't needed because unix-like systems will already execute the text file within the shell.(adapted from this comment)
I used it in my C++ script:
If your compilation line grows too much you can use the preprocessor (adapted from this answer) as this plain old C code shows:
Of course you can cache the executable:
Now, for the truly eccentric Java developer:
D programmers simply put a shebang at the beginning of text file without breaking the syntax:
See: