Keith Thompson said:
[...]
No. Dan Pop gave the correct explanation. Execution does NOT start with
main(), but with the C runtime ("crt") code which sets up a runtime
environment for main(), e.g.,: initializing argc, argv and envp.
I haven't seen anyone point out yet that there is no "envp" argument
to main in C, in a conforming hosted implementation. In nonstandard
extensions to C, of course, there may all sorts of things.
Execution of what? Execution of the user's program starts with main.
What happens before that is implementation-specific; there may or may
not be anything called a "C runtime".
Yet "something" has to pass argc and the argv[] array to main(). While not
specifically defined, it IS guaranteed by K&R.
Not exactly. What's guaranteed by the standard is that in a hosted
implementation, program execution will begin in main, which will have
two arguments if it's defined as having two arguments. (It can also
be defined with no parameters.) The first argument will be an int
with a non-negative value; the second argument is a char ** with
certain guarantees about its value and the value of the char * objects
it points to.
Those guarantees are significant, but they are not strong enough to
require that all hosted implementations actually pass anything useful
to main.
Couldn't that "something" be the OS directly? It doesn't seem to me that
there's anything that would preclude argc/argv being set up for a C (or
whatever) program directly by the shell/command-processor, with the
C-generated executable having an entry point directly at the start of
main().
Whether a hosted implementation's execution environment is
conceptually divided into two entities called "OS" and "C runtime",
or divided up any other way, is purely a matter of definition as far
as C is concerned and completely irrelevant to the initial call to
main.
In my favorite oddball C implementation, EPM C for the AS/400, the
C execution environment is not "bound" to a C program at all; it
is part of a multilanguage execution environment that was loaded
by the OS on a job-by-job basis as needed. The first time an EPM
program is executed in an OS/400 job (which might be an interactive
session, or a batch job, or various other things), the EPM
environment is loaded and initialized. After that, any compiled C
program object can be invoked from anywhere in that job, until the
job ends or the EPM environment is explicitly terminated (by a system
call or user command).