arch detail

arch detail

Friday, September 02, 2011

Crazy C program

I don't know why I love this, but you can actually call main() from inside a C program! Or at least, with GCC 4.4.3 will let you. I wonder if other compilers allow this?

#include 


int main(int argc, char** argv) {
if (argc == 0) {
return 0;
}
else {
printf("%s\n", argv[0]);
main(argc - 1, &(argv[1]));
}
}


Compile it and try:

$ ./a.out a b c d

./a.out
a
b
c
d

1 comment:

Aaron said...

Sure you can, main() is just an ordinary function. It's not even the first function that gets invoked when your program runs. Lots of stuff happens first! The (g)libc does all sorts of crazy initialization stuff like executing constructors from the .ctors section before it even thinks about calling main.

The actually entry point is typically called _start (listed in the ELF program headers) which calls __libc_startmain which trampolines into the glibc initialization code (_dl_runtime_resolve), and on and on. I can't find an easy way to count instructions/functions called before main() gets invoked, but it's pretty seriously hairy.