简体   繁体   中英

How to set multiple variables in target makefile

I have one problem. I cannot set multiple variables depending on target. I need to set two variables for example if makefile has been run with option cpp (target), two variables should be set,but I get only one variable (CC) set. But another is left as default.

cpp:EXTENSION=cpp
cpp:CC=g++
cpp:COMPILE

Please help with this problem.

I cannot set multiple variables depending on target.

In GNU Make , this is typically achieved by analyzing the content of the $(MAKECMDGOALS) variable and then setting the variables depending on the specified goals.

For example, a Makefile:

ifeq ($(filter cpp,$(MAKECMDGOALS)),cpp)
MSG=make cpp was called!
endif

ifeq ($(filter notcpp,$(MAKECMDGOALS)),notcpp)
MSG=make notcpp was called!
endif

all:
        @echo possible targets: cpp, notcpp; false

notcpp cpp:
        @echo $(MSG)

Running the make cpp would print make cpp was called! .

Running the make notcpp would print make notcpp was called! .

(Explanation of the ifeq ($(filter cpp,$(MAKECMDGOALS)),cpp) construct. The $(filter) function looks for the word (first argument, cpp ) in the list (second argument, $(MAKECMDGOALS) ). If it finds the word, it returns it. Otherwise, it returns an empty string. The ifeq then compares the result of the $(filter) function to the sought word: if equal, then the block til endif is parsed/executed. Alternatively, one could write ifneq ($(filter cpp,$(MAKECMDGOALS)),) to test that the result of $(filter) is not an empty string. For more info, see $(filter) and ifeq in GNU Make documentation. Additionally, about general function syntax and how to call a custom function .)

Another possibility is using multiple Makefiles. In the main Makefile, depending on the target you pass the control to the target-specific Makefile, eg:

cpp notcpp:
    $(MAKE) -f Makefile.$@ all

Use of target-specific includes is also a popular option.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM