As the question mentions, how do command line arguments work in C(in general any language). The logical explanation I could think of is, the operating system sets some kind of environmental values for the process when it starts. But if it's true I should not be able to access them as argp[i] etc(I modified the main to expect the 2nd argument as char **argp instead of **argv). Please explain.
相关问题
- Multiple sockets for clients to connect to
- What is the best way to do a search in a large fil
- glDrawElements only draws half a quad
- Index of single bit in long integer (in C) [duplic
- Equivalent of std::pair in C
In a C program the OS creates an array of pointers to zero terminated strings. The count is passed as
argc
and the array is passed asargv
. You already know this. The namesargc
andargv
don't matter. You can use any name. The data types and the order do matter...argv
must beint
andargc
must bechar*[]
orchar**
. Other languages have similar mechanisms. For example C# passes a singlestring[]
argument which is a .NET array and keeps track of it's length internally. More information is available here: http://en.wikipedia.org/wiki/Main_function#C_and_C.2B.2BEnvironment variable names are separate from names of variables in your program.
argc
andargv
are not environment variables... they are variables local tomain()
.To access environment variables use
getenv()
.Update: You wanted to know how these are made available to the program. It is the OS which does that. But before the OS can do so, the program invoking your executable -- the caller -- gets to process your command line. Usually the caller is a shell (
bash
,csh
,zsh
,cmd.exe
) or a desktop environment like GNOME or Windows Explorer. The caller passes these arguments via execve (on *nix) or CreateProcess (on Windows).What ever the name you give to main arguments, what is important is their type and order. To get env vars use this closure:
Is this what you're wondering?
I'll try to explain the implementation a bit more than other answers.
I'm sure there are inaccuracies, but hope it describes the relevant parts well enough.
Under the shell, you type
./myprog a b c
.The shell parses it, and figures out that you want to run
./myproj
with three parameters.It calls
fork
, to create a new process, where./myprog
would run.The child process, which still runs the shell program, prepares an array of 5 character pointers. The first will point to the string
./prog
, the next three are to the stringsa
,b
andc
, and the last is set to NULL.Next, it calls the
execve
function, to run./myprog
with the parameter array created.execve
loads./myprog
into memory, instead of the shell program. It releases all memory allocated by the shell program, but makes sure to keep the parameter array.In the new program,
main
is called, with the parameter array passed to it asargv
.