Week 3 Tutorial — Command Line Arguments & Makefiles

    1. Assume you have the following string declarations:

      char *r = "1";
      char *s = "23";
      char *t = "456";
      

      Write a short program that uses the sscanf() function to sum these 3 strings and print the result on stdout. (When you use sscanf(), you should check that it has successfully read a number.)

    2. Modify the program in the previous exercise to read 3 strings from the command line. The number of command-line arguments should be checked.

  1. Consider the following basic Makefile:

    myprog: myprog.c myprog.h
    	gcc -Wall -Werror -o myprog myprog.c
    

    which contains a rule for myprog.

    1. A rule consists of a target, dependent files (if any), and commands (if any). Identify each of these in this rule.
    2. It is important that a command is preceded by a particular character. What character is that?
    3. If the source file myprog.c has just been modified, what happens when I execute the UNIX command make here?
    4. Alternatively, if the 'timestamp' of the executable myprog is more recent than its source file, what happens when I execute the UNIX command make?

  2. A more complex Makefile is the following.

    CC=gcc
    
    CFLAGS=-Wall -Werror -O
    
    prog1: prog1.c prog1.h
    	$(CC) $(CFLAGS) -o prog1 prog1.c
    prog2: prog2.c prog2.h
    	$(CC) $(CFLAGS) -o prog2 prog2.c
    

    1. What happens when you execute the following commands (assume in each case that both source files have more recent timestamps)?

      1. make prog1
      2. make prog2
      3. make

    2. Extend the Makefile in 2 ways:

      1. the command make all should build both executables, but this is not the default action.
      2. the command make clean should remove appropriate executables and object files, and any core dumps in the current directory.

    3. The UNIX command touch can be used to make the timestamp of a file the current time. For example, the command touch prog1.c will change the timestamp of prog1.c to the current time. Why is this a useful command in relation to make?

    4. What will be the effect of the command touch *.c; make all?

    5. Special macros, or abbreviations, are predefined in the Makefile. Two examples are:

      1. $@ which is an abbreviation of the target name
      2. $< which is an abbreviation of the source filename corresponding to the target

      Modify the Makefile so that the command uses these macros.