Makefile


Notes

  1. use nemiver to debug.

    • gcc/g++ -g hello.c -o hello.o #-g for debug
    • nemiver hello #bin file
  2. The comment character # does not introduce a make comment in the text of commands.

  3. Wildcards: . expands to all the files containing a period. A question mark represents any single character, and […] represents a character class.

  4. .PHONY: clean

  5. Automatic Variables:

    • $@ The name of the current target.
    • $% The filename element of an archive member specification.
    • $< The name of the first prerequisite.
    • $? The names of all prerequisites that are newer than the target, separated by spaces.
    • $^ The names of all the prerequisites, separated by spaces. This list has duplicate names removed since for most uses, such as compiling, copying, etc., duplicates are not wanted.
    • $+ The names of all the prerequisites separated by spaces, including duplicates. This variable was created for specific situations such as arguments to linkers where duplicate values have meaning.
    • $* The stem of the target filename. A stem is typically a filename without its suffix. Its use outside of pattern rules is discouraged.
  6. run makefile with —just-print option to view the execution process

How to write Makefile

  1. single C-file

    1
    2
    hello: hello.c
    gcc -g hello.c -o hello</code></pre>
  2. multiple C-files

    1
    2
    3
    4
    5
    6
    7
    8
    count_words: count_words.o lexer.o -lfl
    gcc count_words.o lexer.o -lfl -ocount_words
    count_words.o: count_words.c
    gcc -g -c count_words.c
    lexer.o: lexer.c
    gcc -g -c lexer.c
    lexer.c: lexer.l
    flex -t lexer.l > lexer.c
  3. set VPATH and CPPFLAGS in implicit rules

    1
    2
    3
    4
    5
    6
    7
    VPATH    = src include
    CPPFLAGS = -I include

    count_words: counter.o lexer.o -lfl
    count_words.o: counter.h
    counter.o: counter.h lexer.h
    lexer.o: lexer.h

    VPATH can be used in a more advanced fashion as follows,

    1
    2
    3
    vpath %.c src
    vpath %.l src
    vpath %.h include
  4. Use library .a. pack .o files into .a, similar as .lib in Windows.

    1
    2
    3
    4
    5
    libcounter.a: libcounter.a(lexer.o) libcounter.a(counter.o)
    libcounter.a(lexer.o): lexer.o
    $(AR) $(ARFLAGS) $@ $<
    libcounter.a(counter.o): counter.o
    $(AR) $(ARFLAGS) $@ $<