Reputation: 61
I want to better understand what's going on under the hood with the command line arguments when a C or C++ program is launched. I know, of course, that argc
and argv
, when passed to main()
, represent the argument count and argument vector, respectively.
What I'm trying to figure out is how the compiler knows to interpret int argc
as the number of arguments passed from the command line. If I write a simple function that attempts to mimic main()
(e.g. int testfunc(int argc, char* argv[])
), and pass in a string, the compiler complains, "Expected 'int' but argument is of type char*" as I would expect. How is this interpreted differently when command line arguments are passed to main()
?
Upvotes: 3
Views: 793
Reputation: 224082
In common C implementations, main
is not the first routine called when your process starts. Usually, it is some special entry point like _start
that is provided by the C library built into your program when you link it. The code at this special entry point examines the command line information that is passed to it (in some way outside of C, particular to the operating system) and constructs an argument list for main
. After that and other work, it calls main
.
Upvotes: 9
Reputation: 134396
You don't pass argc
value on your own (from the command line, for example), it is supplied by your environment (runtime), just like the exact content for argc
.[Note below]
To elaborate, C11
, chapter §5.1.2.2.1, (indicators mine)
The value of
argc
shall be nonnegative.
argv[argc]
shall be a null pointer.If the value of
argc
is greater than zero, the array membersargv[0]
throughargv[argc-1]
inclusive shall contain pointers to strings, which are given implementation-defined values by the host environment prior to program startup. The intent is to supply to the program information determined prior to program startup from elsewhere in the hosted environment. [Note start]If the host environment is not capable of supplying strings with letters in both uppercase and lowercase, the implementation shall ensure that the strings are received in lowercase.[Note end]
Upvotes: 2