Last Updated: January 04, 2021
·
2.077K
· 3demax

self-compiling source code

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

#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
./hello.c

So let's go deeper

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

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"
./"$OUTFILE"
exit
#endif

#include <stdio.h>
int main(){
  printf("hello");
  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

https://github.com/igor-petruk/scriptisto

over 1 year ago ·