2
votes

This is a fairly simple question, but I cannot let it go. I've started working with C again recently (not terribly experienced with it to begin with) so I can better understand what's going on under the hood. 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 (i.e. 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()?

2
The command line isn't passed in as a string, there are quite a lot of magic going on behind the scenes โ€“ Passer By
C runtime startup code takes the argument string (from the OS, in the OS-specific manner), splits it into pieces, and calls main passing those pieces. Or in some cases (Unix-y systems) the OS (more precisely, the shell) parses the string and passes it in pieces to the C runtime. โ€“ Igor Tandetnik

2 Answers

7
votes

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.

2
votes

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 members argv[0] through argv[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]