We had an
ACM programming contest that was to write a program that printed it's own
source code. The history behind these programming contests was that no one ever did them, or they were too hard and too
obstruse (or poorly explained) that they were never quite worth it).
So one day, one kid suggested this contest (that we write a program that prints its own source code in C). The rules were that it had to use
g++ (or
gcc, which ever is your
poison), and the standard
preprocessor (no
perl,
scheme,
JScript,
whatever). The thing was, is that this kid,
who shall remain nameless, had been working on it for
three months (at least). I thought this was stupid and
unreasonable, so I wanted to do something about it. It's been done a
million times on the web (you can do it with number
tables, and you can do it with interesting
character sets and variable choices, etc). I was thinking up a way to do this, and then it hit me.
Let's do it in the preprocessor
That's right. I was determined to
#include the code into itself in some sort of
string, and print it out at
runtime. It forced me to learn a
TON about how the
preprocessor works. I only worked on it for a few hours to mild
success, although I was determined to beat that
guy. I managed to get a program to print it's own source code with nine characters.
"#error hi"
...was
the name of the beast. In the
g++ precompiler, that stops
compilation and dumps out the line it errored out on. Since it was only one
line, it was the entire source. It was so simple and stupid. I did my best to make fun of the stooge who proposed the contest; or at least I made enough people laugh about it to be worth my
headache.
To this day, the #include
solution still eludes me. I go back to it sometimes in a
spare moment. I'll come up with it sometime, but until then, it's still a little funny (and sad). "
They never said it had to compile."