Sunday, July 01, 2007

Writing code at compile time

How do you write a C program, which at compile time allows you to input another program at the terminal. When you run the 1st program, the code that you input at the terminal should execute.

Something like:

bash#gcc -o 1 1.c
#incude
int main(void)
{
printf("Let a thousand ideas bloom :)");
}
^D
bash#./1
Let a thousand ideas bloom :)


So write the code for 1.c. Hint: Assume gcc and any UNIX variant as OS.

As it turns out, the solution is a one liner.

#include "/dev/tty"

While compiling, the macroprocessor tries to open and read from the file /dev/tty, just as it would do for any other include like stdio.h. Since /dev/tty is the terminal, you can now input the second program at the terminal. It get compiled and Bingo! you execute code written at compile time.

4 comments:

Nilesh R. Jaiswal said...

sahi hai...
hope 2 see more such techno info

Unknown said...

hey Anoop, This is fantastic.
Great going buddy!!! :)

Tushar said...

nice!

Anonymous said...

People should read this.