Last Updated: October 28, 2019
· 3demax

self-compiling source code

//&> /dev/null; \
OUTFILE=$(basename "$0" .c); \
gcc $0 -o "$OUTFILE"; \

#include <stdio.h>

int main () {
    printf("hello world!\n");

Save this code as hello.c change executable bit and run as binary

chmod +x hello.c

So let's go deeper

//&> /dev/null; \
OUTFILE=$(basename "$0" .c); \
gcc $0 -o "$OUTFILE"; \

Of course, all lines are independently interpreted by two different programs: gcc and bash.
Both think this is the long commented line, broken into few by backslashes.
And bash thinks this is bash code, and actually executes // as a command, and gives error, but we ignore that fact by redirecting output to /dev/null
Then it goes further, executing this long line until the exit command reached.

This trick was created because of been to lazy to type all the commands to compile and run simple c source code file. But this can be absolutely applied to any compiling language.

@haynesgt have provided even more pretty solution:

#if 0
OUTFILE=$(basename "$0" .c)
gcc $0 -o "$OUTFILE"

#include <stdio.h>
int main(){
  return 0;

Thanks, @haynesgt! That's smart!

2 Responses
Add your response


EPIC! Great alternative for Makefile for small one-file source.

over 1 year ago ·

Also consider using a tool that I wrote just for what, works cleanly with any compiled language


8 months ago ·