We know that in a C-program the function main can take two arguments, signature being,

int main(int argc, char** argv)

How do we pass these arguments to main? One way is to launch the program via command line. Let us understand it step by step with an example. We take the sample example from our “The Book of C”.

#include <stdio.h>

int main (int argc, char * argv[]) {
    printf (“%d\n”,argc);

    for (int i=0; i<argc; i++){
        printf(“%s\n”, argv[i]);
    }

return -1;
}

Compile the program on command line

First let us learn how to compile the C-program via command line. To compile, we invoke gcc (C-compiler) from command line to compile the code

user@server:~$ gcc test.c -o test

The ‘-o’ flag to gcc is used to specify the name of the binary to be produced by the compiler. By default, the name of binary file is a.out. After successful compilation we can find the binary file in same directory:

user@server:~$ ls -l test
-rwxrwxr-x 1 user user 8656 Dec 20 11:50 test

Launch the binary from command line

To execute the binary from command line, we type the binary name on command prompt followed by parameters. Let us execute the binary that we compiled in above section:

user@server:~$ ./test one two three four five

The output of above program on console will be

6
./test
one
two
three
four
five

As you can see, the output contains

  • 6 – the number of parameters passed on command line. Note that the name of the binary too is counted in number of arguments.
  • The input strings are printed one by one. Note that the name of the binary as well is listed as one of the input arguments.