Saturday, December 12, 2009

c program without main

/* prog_without_main.c */
_start()
{
_exit(my_main());
}
int my_main(void)
{
printf(“Hello\n”);
return 42;
}
And use this command (% is command prompt) to compile:
%gcc -O3 -nostartfiles prog_without_main.c

Try compiling this example:
#include
#define decode(s,t,u,m,p,e,d) m##s##u##t
#define begin decode(a,n,i,m,a,t,e)
void begin()
{
printf(“hello”);
}
here is how it works once we say define we need to understand that
#define x y
then ‘x’ ix replaced by ‘y’
similarly in this case
#define begin decode(a,n,i,m,a,t,e)
decode(a,n,i,m,a,t,e) is replaced by m##a##i##n
bcoz s is replaced by a,t by n,u by i and so on
s->a
t->n
u->i
m->m
p->a
e->t
d->e
now the statement becomes
void m##a##i##n
And u must be knowing that ## is used for string concatenation so it becomes
“main”
finally the code crops down to
void main()
{
printf(“hello”);
}

Here we are using preprocessor directive #define with arguments to give an impression that the program runs without main.But in reality it runs with a hidden main function.

The ‘##‘ operator is called the token pasting or token merging operator.That is we can merge two or more characters with it.

NOTE: A Preprocessor is program which processess the source code before compilation.

Look at the 2nd line of program-

#define decode(s,t,u,m,p,e,d) m##s##u##t

What is the preprocessor doing here.The macro decode(s,t,u,m,p,e,d) is being expanded as “msut” (The ## operator merges m,s,u & t into msut).The logic is when you pass (s,t,u,m,p,e,d) as argument it merges the 4th,1st,3rd & the 2nd characters(tokens).

Now look at the third line of the program-

#define begin decode(a,n,i,m,a,t,e)

Here the preprocessor replaces the macro “begin” with the expansion decode(a,n,i,m,a,t,e).According to the macro definition in the previous line the argument must de expanded so that the 4th,1st,3rd & the 2nd characters must be merged.In the argument (a,n,i,m,a,t,e) 4th,1st,3rd & the 2nd characters are ‘m’,'a’,'i’ & ‘n’.

So the third line “int begin” is replaced by “int main” by the preprocessor before the program is passed on for the compiler.That’s it…

The bottom line is there can never exist a C program without a main function.Here we are just playing a gimmick that makes us beleive the program runs without main function, but actually there exista a hidden main function in the program.Here we are using the proprocessor directive to intelligently replace the word begin” by “main” .In simple words int begin=int main.

No comments:

Post a Comment