473,796 Members | 2,632 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Question on main

who calls main() ?

Aug 5 '06 #1
14 1681
On 2006-08-05, Su********@gmai l.com <Su********@gma il.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********@gmai l.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********@gmai l.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********@gmai l.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********@gmai l.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
implementation s, 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********@gmai l.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 responsibilitie s
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********@gmai l.com <Su********@gma il.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********@gmai l.com <Su********@gma il.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************ **********@b28g 2000cwb.googleg roups.com>
<Su********@gma il.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
"uninitiali zed 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 -- "++globalva r" 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********@gmai l.com <Su********@gma il.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

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

Similar topics

4
1795
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 will no longer work to assist with formatting the data. I have a Phone Number field that is Varchar 10 The numbers have imported without the leading zero.
16
637
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
2328
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 like to implement in the most efficient was possible. So I summoned up my programming intellect and asked myself: Do I want to have members such as int a, b, c, d, e or a single member such as int a. So I wrote the following snippet and compiled it...
11
6920
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
1692
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 thing was what actually turn this while loop into an endless loop instead of waiting for user response it'll would skip right over it. Could someone with the time explain this to me what would make it behave like this int pts1, pts2, pts3,...
7
1283
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 show up (and the first form disappear), and i also want another button on the second form to return to the first form.
7
1390
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
3583
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 one data field - but i'm not sure) :-) Background info:
4
1508
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. This works fine and great. My problem is w/ menus. Each Channel returns a Popup Menu (based on an interface requirement) that gets placed in the Main Framework's main menubar. Again, works fine. However, what i'm unsure of is the eventhandler...
6
6241
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 out anything when the child threads are running. The child threads do sleep after some work. Instead should I make the child threads wait() and make the main thread notifyAll() after printing ? public class MainThread { WorkerThread t1, t2;...
0
9685
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9533
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10239
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10190
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9057
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6796
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5447
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5579
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4122
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

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.