Change Makefile variable value depending on a target

后端 未结 2 707

I am not proficient with makefiles, but am used to simple ones. Right now, I have a task on hand.

I need to compile and link a test application with a different libr

2条回答
  •  余生分开走
    2020-12-31 10:03

    I don't think you can alter variable depending on a target. Assume you invoke

    make TARGET1 TARGET2
    

    What value would the CFLAGS have then?

    In this case, you can use non-pattern rules to distinguish targets.

    TARGET1: a.c
        @echo [CC] $< ...
        $(CC) -I INCLUDEPATH1 ...
    
    TARGET2: a.c
        @echo [CC] $< ...
        $(CC) -I INCLUDEPATH2 ...
    

    To decrease repetition, you may also use variables and "functions". Then, you could re-use what would be the body of your pattern rule in different rules.

    define compile_cmd
        @echo [CC] $< ...
        $(CC) -I $1 -l$2 $(CFLAGS)
    endef
    
    TARGET1: a.c
        $(call compile_cmd,INCLUDEPATH1,LIB1) -o $@ $<
    
    TARGET2: a.c
        $(call compile_cmd,INCLUDEPATH2,LIB2) -o $@ $<
    
    %.o: %.c
        $(call compile_cmd,INCLUDEPATH_DEFAULT,LIB_DEFAULT) -o $@ $<
    

    That would make a nice enough and flexible makefile that suits your needs.

提交回复
热议问题