e1htcg
Last Updated: February 25, 2016
·
973
· 3demax
B91775f48b21e9eb536ee9b955675ed4

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!

Say Thanks
Respond

1 Response
Add your response

3466
40899089b857df34ab04b17f01b00831

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

over 1 year ago ·
Filed Under