SiteBanner

Many command-line programs - even GUI executable 'C' programs utilize 'arguments'.

 

  1. Open a terminal window and navigate to your desired work subdirectory.
  2. Open a text editor; Copy then paste the boxes below into your editor.
  3. Save the first block of code below as 'goc'.  Save the second as 'main.c'.
  4. In the terminal window, make shell script 'goc' executable:  "chmod +x goc"
  5. Invoke the compile script with the line:   "./goc pgm3"
  6. List the files present in the terminal.  There should be 3:  goc, main.c, pgm3.
  7. Invoke the newly-created program with "./pgm3 123"

 

#!/bin/bash
# invoke this script with desired name of executable
# 'C' source code is expected in file 'main.c'
# flag the compiler to provide more error and warning checks
pgmname=$1
gcc main.c -Wall -o $pgmname

 

(right-click to download)

/* Here's source for 'pgm3' */

#include <stdio.h>
#include <stdlib.h>

// argc = count of arguments argv = the individual arguments - type char string
int main(int argc, char *argv[]) {
int value1;

value1 = atoi(argv[1]);

printf("The number you gave me is %d\n", value1);

// we return the command-line argument value to the shell
return(value1);
}  

 

If we execute, say, "./mypgm donkey 2457 meatloaf 1000", the count of arguments ('argc') will be 5. Not 4, because 'argc' will include in the count the name of the executable itself. Each argument is accessed through 'argv[]' (which is an array of character strings). In this way: argv[0] contains 'mypgm' argv[1] contains 'donkey' argv[2] contains '2457' argv[3] contains 'meatloaf' argv[4] contains '1000' When a terminal window program finishes, it frequently returns a numeric value to the shell. We can find out that value by entering "echo $?" immediately after the program exits. 

  • argv[0] contains 'mypgm'
  • argv[1] contains 'donkey'
  • argv[2] contains '2457'
  • argv[3] contains 'meatloaf'
  • argv[4] contains '1000'