Sunday, April 13, 2008

C program with out main()

*********************************
writing C program without main()
*********************************

I am using the following program to compile and run with out main()

//MyFile.c
#include<stdio.h>
#include<stdlib.h>

int MyMain(){
printf("Program with out main");
exit(0);
}

compile the program with gcc using the following options

gcc -o MyFile -nostartfiles -e MyMain -lc MyFile.c

u can execute the MyFile using ./MyFile

***********************************************
the options mean this
***********************************************

-o name create a executable with name

-nostartfiles
Do not use the standard system startup files when linking. The
standard system libraries are used normally, unless -nostdlib or
-nodefaultlibs is used.


-e entry
--entry=entry
Use entry as the explicit symbol for beginning execution of your
program, rather than the default entry point. If there is no sym‐
bol named entry, the linker will try to parse entry as a number,
and use that as the entry address (the number will be interpreted
in base 10; you may use a leading 0x for base 16, or a leading 0
for base 8).

-lc link with the standard c library

***********************************************

problem faced :


if u dont call the function exit(0) at the end it will give a segmentation fault.

when tried to create object file separetely with no startupfiles option and link using the linker(ld) the output file created is not executing.

gcc -c -nostartfiles MyFile.c
ld -e MyMain -lc MyFile.o

if u see the object dump of both files genereted both are same.

objdump --disassemble a.out
objdump --disassemble MyFile

please tell me whats wrong with second procedure.



No comments: