Understanding Makefile with .c=.o and $<

后端 未结 2 1660
清歌不尽
清歌不尽 2021-02-04 16:15

This is my first Makefile, and I can\'t figure out some of the syntax used. The questions are marked below:

C := gcc

CFLAGS := -Wall -Werror -std=

PROG := progr         


        
2条回答
  •  清酒与你
    2021-02-04 16:47

    First of all, your Makefile has a bug, it does not make the intended targets. Did you try it?

    Second, it is not well written; not following best current practices.

    So I will first show you the better version of your Makefile, both correct, as well as written with the best practices:

    CFLAGS := -Wall -Werror -std=
    
    SRCS := program_1.c \
        program_2.c \
        program_3.c
    
    OBJS := ${SRCS:c=o} 
    PROGS := ${SRCS:.c=}
    
    .PHONY: all
    all: ${PROGS}
    
    ${PROGS} : % : %.o Makefile
        ${CC} $< -o $@
    
    clean:
        rm -f ${PROGS} ${OBJS}
    
    %.o: %.c Makefile
        ${CC} ${CFLAGS} -c $<
    

    Now, the answers to your questions are:

    ${SRCS:.c=.o} means, take the variable value ${SRCS}, which is a string composed of words separated by spaces, and for each word, replace the suffix .c with .o . I dropped . in my code because it is not needed and it is common to replace only suffixes after the dot.

    This syntax is similar to bash string suffix replacement (for one word) if you are familiar with that.

    $< when used in the "recipe", means "the first prerequisite" - the first thing after the : in the line above.

    and the last question is no longer relevant: .o.c syntax is obsolete and not recommended currently.

    Please take a look at my "10 Commandments" - my answer at this post:

    makefile enforce library dependency ordering

    , they will give you an idea about the best practices. Then you can also read up in the GNU Make manual, about the terms above in quotes, that I did not explain here.

提交回复
热议问题