473,386 Members | 1,823 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

Question on main

who calls main() ?

Aug 5 '06 #1
14 1647
On 2006-08-05, Su********@gmail.com <Su********@gmail.comwrote:
who calls main() ?
Your operating system.

--
Andrew Poelstra <http://www.wpsoftware.net/projects>
To reach me by email, use `apoelstra' at the above domain.
"Do BOTH ends of the cable need to be plugged in?" -Anon.
Aug 5 '06 #2
Su********@gmail.com said:
who calls main() ?
You can! The main function can be called recursively.

In general, though, main is called by "the system". For example, it might be
called by the startup code that some (most?) linkers inject into the final
executable program. Or it might simply be translated into a start address
that the OS automatically jumps to when the program is invoked. The C
Standard doesn't specify this. It specifies only that, on hosted
implementations, the entry point is main. So I suppose one might say "the
host" calls main.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at above domain (but drop the www, obviously)
Aug 5 '06 #3
hmmm.... 'the system calls main' is precisely the answer I am finding
in documentation everywhere.....and I am finding it sort of vague...

Where does the C-runtime lib & its initialization fit into this?

Thanks a lot
Sumit

Richard Heathfield ne likha tha:
Su********@gmail.com said:
who calls main() ?

You can! The main function can be called recursively.

In general, though, main is called by "the system". For example, it might be
called by the startup code that some (most?) linkers inject into the final
executable program. Or it might simply be translated into a start address
that the OS automatically jumps to when the program is invoked. The C
Standard doesn't specify this. It specifies only that, on hosted
implementations, the entry point is main. So I suppose one might say "the
host" calls main.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at above domain (but drop the www, obviously)
Aug 5 '06 #4
Ico
Su********@gmail.com wrote:
hmmm.... 'the system calls main' is precisely the answer I am finding
in documentation everywhere.....and I am finding it sort of vague...

Where does the C-runtime lib & its initialization fit into this?
That depends on your system. On most platforms, the C library provides
some startup code (often called crt0 or something alike) which does some
tasks to prepare the environment for running C code. This includes
things like setting up the stack, initializing memory, loading data
segments, clearing bss, etc. When this is all done, your main() is
called. When main() returns, control is passed back to the startup code
again, who can clean things up and terminate the process.

On the other hand, nothing of this is part of the C language or -standard:
C itself does not know anything about data or bss segments, startup
code, et ce tera.
>
Thanks a lot
Sumit

Richard Heathfield ne likha tha:
>Su********@gmail.com said:
who calls main() ?

You can! The main function can be called recursively.

In general, though, main is called by "the system". For example, it might be
called by the startup code that some (most?) linkers inject into the final
executable program. Or it might simply be translated into a start address
that the OS automatically jumps to when the program is invoked. The C
Standard doesn't specify this. It specifies only that, on hosted
implementations, the entry point is main. So I suppose one might say "the
host" calls main.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at above domain (but drop the www, obviously)
--
:wq
^X^Cy^K^X^C^C^C^C
Aug 5 '06 #5
Su********@gmail.com wrote:
hmmm.... 'the system calls main' is precisely the answer I am finding
in documentation everywhere.....and I am finding it sort of vague...

Where does the C-runtime lib & its initialization fit into this?
In ways the language does not specify.

There's quite a lot that goes on before main() is called
for the first time: static-duration objects are given their
initial values, the FILE* streams stdin, stdout, and stderr
are initialized, the arguments argc and argv of main() are
somehow obtained from the environment, and so on. Likewise,
quite a lot goes on after the program ends: atexit() functions
are called, open FILE* streams are flushed (if necessary) and
closed, and the program's exit status is somehow communicated
back to the environment.

The C language requires that all these things must happen,
but says nothing about how the implementation must get them to
happen. Different implementations will manage things differently:
For example, implementation X might open stdin/stdout/stderr and
then call main(), while implementation Y might use some kind of
trickery to cause them to be opened automatically when and if the
program uses them. Implementation Z might store zeroes in all the
static-duration variables that aren't initialized explicitly, while
implementation ZZ might arrange for them to be created and zeroed
the first time they're referenced. The C language -- and you, as
a C programmer -- need not worry about how all these things are
done, only that they *are* done. "Somehow."

Now, if you are an implementor of C, this is obviously not
satisfactory. The language tells you what your responsibilities
are, but gives few hints about how you are to fulfill them. This
is a problem in some ways, because the language provides little
guidance. On the other hand, by not prescribing "how" the language
gives you the maximum flexibility to accommodate and exploit the
special features of your platform. "The ends justify the means"
is the language's attitude toward your work.

For information on how a specific implementation goes about
tasks of this sort, refer to that implementation's documentation --
there's extensive documentation for the FSF/gnu/Linux melange, for
example. But from the point of view of the C language, all these
things just happen, inexplicably and magically, as if Santa Claus
and the Tooth Fairy had teamed up to coddle the programmer.

--
Eric Sosman
es*****@acm-dot-org.invalid
Aug 5 '06 #6
Andrew Poelstra wrote:
On 2006-08-05, Su********@gmail.com <Su********@gmail.comwrote:
>who calls main() ?

Your operating system.
I don't have an operating system, but I do have a main...
Aug 5 '06 #7
dbtid wrote:
Andrew Poelstra wrote:
>On 2006-08-05, Su********@gmail.com <Su********@gmail.comwrote:
>>who calls main() ?

Your operating system.

I don't have an operating system, but I do have a main...
Maybe 'operating environment' would be a better answer. That is
anything from an address in ROM jump table to a desktop OS.

--
Ian Collins.
Aug 5 '06 #8
In article <11**********************@b28g2000cwb.googlegroups .com>
<Su********@gmail.comwrote:
>hmmm.... 'the system calls main' is precisely the answer I am finding
in documentation everywhere.....and I am finding it sort of vague...
Probably because it is (deliberately) vague. :-)

As Eric Sosman noted elsethread, the method is up to the implementation.
It might be illustrative (if borderline off-topic, and probably on
the "off" side of the border-line) to look at two real implementations,
however.

The first implementation to consider is BSD/OS on the i386. Here,
when you compile a program with:

shlicc -o foo foo.c -ljpeg -lm

you get an executable named "foo" that contains:

- your own code,
- some startup code, and
- references to the shared libraries used (libjpeg, libm, and libc).

The startup code:

- saves argc and argv (actually just one register that points to
a system-provided data structure) and __environ for getenv() etc
- ensures that file descriptors 0, 1, and 2 are open
- locates the shared libraries, opening them and mapping them in
at the desired locations (text and initialized data, with
"uninitialized data" mapped to zero-fill space)
- calls any initialization routines in those shared libraries
(this is really for C++; pure C code never has any)
- calls your main(), passing the saved argc and argv (and a
third parameter which you may safely ignore)
- takes whatever value your main() returned and calls exit()

Initialization of static-duration data for your program -- whether
ordinary initialized variables like:

int globalvar = 3;
void f(void) { static int localstatic = 42; ... }

or uninitialized ("bss", Block Started by Symbol) zero-fill data
-- is handled automatically by the system. However, static-duration
data for shared libraries is handled by the startup code (with a
lot of help from the system; it winds up being just three __mmap()
calls).

The system has already provided a stack for automatic varibles at
the time the startup code is entered, so nothing need be done there.
The three standards streams (stdin, stdout, stderr) use initialized
data, so only the three "file descriptors" (0,1,2) need to be
handled in the startup code.

The second implementation to consider is a typical ROM-based system
(slightly modified to make it a "hosted" environment). Here, when
you compile your program, you get a "ROMable image", which you load
into some kind of programmable read-only memory (typically an EEPROM
or, today, flash memory). When you first power-up the device --
whether it is a cell phone or a digital video recorder or a
defibrillator or whatever -- it executes some startup code.

This startup code:

- depending on hardware involved, sets up devices like the CPU
clock, memory bank switchers, and so on (this code is often
very sensitive and tricky since a lot of it cannot refer to
memory, as the memory controlling hardware is not yet set up)
- tests and/or clears RAM (initializing ECC memory if needed)
- copies the ROM-image initialized data to the data area
(remember, the runtime code cannot refer directly to the ROM
data because the ROM is read-only -- "++globalvar" would
leave the variable unchanged!)
- zeros out other data if needed (the ECC setup may have zeroed
all of RAM already)
- creates a stack (this is actually usually done a bit earlier but
it interacts with memory-initialization so I moved it here)
- calls the C library's "set up stdin, stdout, stderr" routines
- makes up a fake argv, if desired
- calls your main(), passing 0 for argc
- if your main() returns, attempts to display a "rebooting" message
and then repeats as much of the above as needed

As you should now see, while there are similarities, the actual
code for these two implementations is quite different.
--
In-Real-Life: Chris Torek, Wind River Systems
Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W) +1 801 277 2603
email: forget about it http://web.torek.net/torek/index.html
Reading email is like searching for food in the garbage, thanks to spammers.
Aug 6 '06 #9
MQ

dbtid wrote:
Andrew Poelstra wrote:
On 2006-08-05, Su********@gmail.com <Su********@gmail.comwrote:
who calls main() ?
Your operating system.

I don't have an operating system, but I do have a main...
Well, what do you have? You have a program obviously, whose entry
point is main. An operating system is something like Windows, Linux,
etc that provides some way of loading and executing your program. In
Windows this usually means double-clicking the program's icon. Can you
explain more about what you are trying to do?

MQ

Aug 6 '06 #10
"Chris Torek" <no****@torek.netwrote in message
news:eb********@news2.newsguy.com...
In article <11**********************@b28g2000cwb.googlegroups .com>
<Su********@gmail.comwrote:
>>hmmm.... 'the system calls main' is precisely the answer I am
finding
in documentation everywhere.....and I am finding it sort of vague...

Probably because it is (deliberately) vague. :-)

As Eric Sosman noted elsethread, the method is up to the
implementation. It might be illustrative (if borderline off-topic,
and
probably on the "off" side of the border-line) to look at two real
implementations, however.

The first implementation to consider is BSD/OS on the i386. Here,
when you compile a program with:

shlicc -o foo foo.c -ljpeg -lm

you get an executable named "foo" that contains:

- your own code,
- some startup code, and
- references to the shared libraries used (libjpeg, libm, and
libc).

The startup code:

- saves argc and argv (actually just one register that points to
a system-provided data structure) and __environ for getenv() etc
- ensures that file descriptors 0, 1, and 2 are open
- locates the shared libraries, opening them and mapping them in
at the desired locations (text and initialized data, with
"uninitialized data" mapped to zero-fill space)
- calls any initialization routines in those shared libraries
(this is really for C++; pure C code never has any)
- calls your main(), passing the saved argc and argv (and a
third parameter which you may safely ignore)
- takes whatever value your main() returned and calls exit()

Initialization of static-duration data for your program -- whether
ordinary initialized variables like:

int globalvar = 3;
void f(void) { static int localstatic = 42; ... }

or uninitialized ("bss", Block Started by Symbol) zero-fill data
-- is handled automatically by the system. However, static-duration
data for shared libraries is handled by the startup code (with a
lot of help from the system; it winds up being just three __mmap()
calls).
An example of "who" accomplishes these things (info from Linux, but
any POSIX/ELF system should be similar):

1. The kernel loads the program image into memory when you do an
exec()
2. If there's dynamic objects linked, ld.so is called to load them and
link them into the image
3. The kernel examines the ELF header to find the entry point (usually
called _start())
4. The kernel jumps to that address
5. _start() handles the initialization tasks Chris lists above
6. _start() calls your main()
7. When main() returns or exit() is called, _start() does all the
cleanup tasks listed above
8. Last, _start() executes a syscall to the kernel to let it know the
process is finished

(I might have step 2 in the wrong place; _start() may call ld.so
instead of the kernel)

Another example is DOS COM files. DOS simply loads the file into
memory and jumps to a particular offset in that memory image. That
location is where the linker puts the equivalent of _start(), and then
execution proceeds roughly as above from step 5.

Every implementation is going to be different, but it needs to do
roughly the same things, so they'll all look roughly the same.

S

--
Stephen Sprunk "God does not play dice." --Albert Einstein
CCIE #3723 "God is an inveterate gambler, and He throws the
K5SSS dice at every possible opportunity." --Stephen Hawking

--
Posted via a free Usenet account from http://www.teranews.com

Aug 6 '06 #11
<Su********@gmail.comwrote
who calls main() ?
Normally there is rule about where execution of binaries starts.
An obvious one is that the first byte of the file is the first machine
instruction.

However normally programs require a bit of start-up and end code. There
might be a routine to initialise all the zero areas of memory to zero, for
example. Almost certainly there also needs to be code to set up the
command-line arguments.
So the compiler will typically put this start-up code in the start" position
of the program, and it will the call main().

If you look at assembly language programing on your system, you will get a
better idea of the conventions used.
--
www.personal.leeds.ac.uk/~bgy1mm
freeware games to download.

Aug 6 '06 #12
"MQ" <mi**************@gmail.comwrites:
dbtid wrote:
>Andrew Poelstra wrote:
On 2006-08-05, Su********@gmail.com <Su********@gmail.comwrote:
who calls main() ?
Your operating system.

I don't have an operating system, but I do have a main...

Well, what do you have? You have a program obviously, whose entry
point is main. An operating system is something like Windows, Linux,
etc that provides some way of loading and executing your program. In
Windows this usually means double-clicking the program's icon. Can you
explain more about what you are trying to do?
Presumably dbtid is using an embedded system, and the program runs on
the "bare metal".

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Aug 6 '06 #13
In article <11**********************@i3g2000cwc.googlegroups. com>,
MQ <mi**************@gmail.comwrote:
>dbtid wrote:
>Andrew Poelstra wrote:
On 2006-08-05, Su********@gmail.com <Su********@gmail.comwrote:
who calls main() ?
Your operating system.
>I don't have an operating system, but I do have a main...
>Well, what do you have? You have a program obviously, whose entry
point is main. An operating system is something like Windows, Linux,
etc that provides some way of loading and executing your program.
There have been a number of claims made over the years that,
technically speaking, Windows is not an operating system.
I didn't follow those debates; it is possible they only apply to
the versions not based upon NT.
--
All is vanity. -- Ecclesiastes
Aug 6 '06 #14
Walter Roberson said:

<snip>
There have been a number of claims made over the years that,
technically speaking, Windows is not an operating system.
I suppose that depends on your definition of "operating system". I tend to
think of "operating system" as meaning "system that is operating". And
Windows systems have always been a bit shaky when it comes to operating.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at above domain (but drop the www, obviously)
Aug 6 '06 #15

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
by: Scott Berry | last post by:
This is a little frustrating, because it should be easy. I have an application that has been converted to SQL Server 2000 from MS Access 97. New data is loaded each week and one of my old queries...
16
by: ^_^ | last post by:
conversion from: a="a"; to a=0x????; If there are many unicode strings to convert, how can I do batch-conversion?
38
by: aaronfude | last post by:
I'm working on a scientific computing application. I need a class called Element which is no more than a collection of integers, or "nodes" and has only on method int getNode(int i). I would...
11
by: Sweety | last post by:
hello to all members, i have strange question in C. main() { printf("%d",main) ; } here o/p is same for all m/c in TC++ version 3.0 i.e 657. I think this is not garbage.
24
by: Tweaxor | last post by:
This has been puzzling me all this week. This is actually a homework assignment from last semesmter. But the teacher wouldn't tell us why certain things didn't work, but it didn't just work. My...
7
by: Trev | last post by:
Hey, I just want to know (i know i should know this) how can i show up another form? I have 2 forms and the first one has a button on it that when i click the button i want the second form to...
7
by: Tiraman | last post by:
Hi , I am using allot the try catch in my code and the question is if it is good ? it will decrease my performance ? one more question
29
by: MP | last post by:
Greets, context: vb6/ado/.mdb/jet 4.0 (no access)/sql beginning learner, first database, planning stages (I think the underlying question here is whether to normalize or not to normalize this...
4
by: Doug Handler | last post by:
Hi, I've developed a plug-in application that basically is constructed of 2 pieces 1). the "main framework" 2). channels. Using Reflection in the Main Framework, i dynamically load Channels. ...
6
by: Padhu Vinirs | last post by:
JDK 1.4 on WinXP. I have 2 threads started from the main thread. I would like to print some status of the child threads from the main thread periodically. But I dont see the main thread to print...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.