Overview ========== Command Line arguments (using getopt) Header Files Makefiles Homework 3 The Game The board Wining/evaluation Command line arguments ====================== The arguments are passed to the program as an array of strings. The 0 argument is always the name of the program. So argument 1 is array position 1. Example: void main(int argc, char **argv) { int cnt; printf ("I was invoked as %s\n", argv[0]); printf ("My arguments were:\n"); for (cnt=1; cnt < argc; cnt++) printf ("\t%d : %s\n", cnt, argv[cnt]); } Most programs take options like $ prog -v 1 txtfile But options are a pain... 1. See if the argument begins with - 2. Decode option (plus arguments to options) char *filename; for (cnt=1; cnt < argc; cnt++){ char *opt = argv[cnt]; if (opt[0] == '-') { switch (opt[1]) { case 's': size = atoi (argv[cnt+1]); cnt++; break } }else { filename = argv[cnt]; } } printf ("\t%d : %s\n", cnt, argv[cnt]); Simpler way ------------ Do 'man -3C getopt' to this explained fully #include main(int argc, char **argv) { while ((c = getopt(argc, argv, "v:")) != EOF) switch (c){ case 'b': verbose = atoi (optarg); break; default: fprintf (stderr, "usage: prog [-v verbose_lvel] textfile\n"); exit (0); } printf ("argument was %s\n", argv[optind]); } Header Files ============= Split your code into modules including variable + functions Why? 1. Modularity (easier to understand big picture) 2. Reuse (can copy code from one homework to another) Ex. Put all the functions that work on a board in one place (board.c) board.c -------- typedef struct board { int *bins; int player; int terminal; } Board; Board *alloc_board(int bins) { ..} void free_board (Board*){ .. } void board_copy (Board *to, Board *from) { ... } >>Now write a main.c that uses those function main.c ------- main() { Board *b = alloc_board (13) ... } >>But we need to declare the functions --->could just copy all the suff?) --->Why is this not a good idea? >>Make a header file! board.h ------- #ifndef BOARD_H #define BOARD_H typedef struct board { int *bins; int player; int terminal; } Board; Board *alloc_board(int bins); void free_board (Board*); void board_copy (Board *to, Board *from); #endif /* BOARD_H */ >> Now we add the line #include "board.h" (why "? -- <> are for system includes "" are for yours) >> to both board.c and main.c -- Each "sees" the exact same solution. ---> Why did I put ifdef's around the header file? Makefile --------- Compiling multiple files gcc -c board.c gcc -c main.c gcc -o mancala main.o board.o After editing board.c you forget to recompile Makefile -------- # Board depends on board.o and main.o board : board.o main.o gcc -o mancala main.o board.o # board.o : board.c board.h gcc -c board.c main.o : main.c board.h gcc -c main.c >> Run by typing % make Homework 3