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.
问题:
回答1:
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 strings a
, b
and c
, 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 as argv
.
回答2:
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 as argv
. You already know this. The names argc
and argv
don't matter. You can use any name. The data types and the order do matter... argv
must be int
and argc
must be char*[]
or char**
. Other languages have similar mechanisms. For example C# passes a single string[]
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.2B
Environment variable names are separate from names of variables in your program. argc
and argv
are not environment variables... they are variables local to main()
.
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).
回答3:
What ever the name you give to main arguments, what is important is their type and order. To get env vars use this closure:
int main(int argc, char ** myCommandLineArguments, char ** myEnvironmentVars)
Is this what you're wondering?