Compiler errors won’t cause as many funny consequences with
gcc "$0" -o "$@".out && exec ./"$@".out || exit $? # I'd use ${0%.c} not $@
Love this trick too, but the difference, as far as I understand, is that it only works with a Bourne(-compatible) shell, whereas shebangs or binfmt_misc also work with exec().
The shell treats the first line as a comment. It executes the second line, which eventually exec's the binary so the rest of the file do not matter to the shell.
And the compiler treats the first line as a preprocessor directive, so it ignores the second line.
I initially misread/mistook the first line for a shebang.
You can also #embed the compiler binary, and execve it to much the same effect as binfmtc. I explored that trick for an IOCC entry that was never submitted because it ended up far too readable.
Yes, but it's not worth it. It's better to forget gcc and use tcc instead, which has the -run flag to compile and run without creating any intermediate file. It's also much quicker than gcc.
There's a similar cute trick for compiled OCaml scripts that we use with nbdkit: https://libguestfs.org/nbdkit-cc-plugin.3.html#Using-this-pl...
In the trivial case exposed here where there are no additional arguments to pass to the .c program, the shell executes
and it works "by chance".In a more complex scenario where print.c expects some parameters, it won't work. For example,
will result in the shell trying to invoke which makes no sense.Are you sure you didn't intend $0 instead of $@ ?
OTOH we're trying to write self-compiling executable C scripts, so the safety, correctness and good sense ships sailed a while back.
The shell treats the first line as a comment. It executes the second line, which eventually exec's the binary so the rest of the file do not matter to the shell.
And the compiler treats the first line as a preprocessor directive, so it ignores the second line.
I initially misread/mistook the first line for a shebang.
What is the benefit of registering an extension via binfmt_misc?
https://rosettacode.org/wiki/Multiline_shebang#C
Isn't that already legitimized by configure scripts, compiler command lines and Make files?
https://github.com/codr7/hacktical-c/tree/main/dynamic