tags:

views:

240

answers:

4

Hi is there anyway to write a c program without main function.If so,point it out plz!

+3  A: 

No. C is totally based off of the assumption that you start the program in main(). Anyway, why would you want this? This would make inconsistencies for other programmers reading your code.

Richard J. Ross III
Sort of. That's true for *hosted* environments, but *freestanding* environments are free to deal with program startup however they want. Of course, then it's entirely implementation-defined territory.
jamesdlin
+6  A: 

C defines the entry point in a hosted environment to be main. In a "freestanding" environment, however, the entry point can have some other name. That's about the only latitude the language (at least officially) allows in that particular respect.

Jerry Coffin
+3  A: 

The following linker abuse

char main[] = { /* Machine code for your target implementation */ };

will work on some platforms.

Alexandre C.
This is not in .data segment, on windows UAC must be terminate this application of executing code from non .data segment.
Svisstack
+1 hehe, nice hack of the question ;-)
Michael
@Michael, yep but will work only on a few platforms (see @Svisstack's comment)
Alexandre C.
I don't think that this abuse is covered by the standard. There it clearly states that `main` must be a function. Function pointers and data pointers are incompatible in C99.
Jens Gustedt
@Jens: Linkers usually don't care about the C standard, `main` is just a symbol.
Alexandre C.
Linkers may accept it, but that doesn't make this a C program. Linkers have been known to even accept * gasp * C++ programs.
MSalters
@Alexandre C: first you said, that this is a valid C program, which it isn't, so your answer is at least misleading, in not pointing to a proper solution but to a hack. And then, more seriously, on a given platform function pointers may just be wider than data pointers and just anything may happen if you try to execute such a "symbol"
Jens Gustedt
@Jens: of course this is a hack, and it won't work on some (many?) platforms. I correct my answer to match your criticism.
Alexandre C.
+2  A: 

Maybe this could work: http://www.gohacking.com/2008/03/c-program-without-main-function.html

An alternative is to write a C program and look at the Assembly output: http://users.aber.ac.uk/auj/voidmain.shtml

More information about what happens before main() is called can be found here (How Initialization Functions Are Handled): http://gcc.gnu.org/onlinedocs/gccint/Initialization.html

Codeape