简体   繁体   中英

How do I put conditionals in makefile pattern rules?

I have an included file for a makefile that has these rules:

$(OUT_DIR)/%.0: %.c
    $(CC) $(CFLAGS) -c -o $@ $<
    $(CC) $(CFLAGS) -E -P $< -o $(OUT_DIR)/$<.preproc
    $(CC) $(CFLAGS) -E -dD $< -o $(OUT_DIR)/$<.macros

Works great. But, for some targets, I only want this:

$(OUT_DIR)/%.0: %.c
    $(CC) $(CFLAGS) -c -o $@ $<

can I do something like this using a predefined (or command line) variable:

$(OUT_DIR)/%.0: %.c
    $(CC) $(CFLAGS) -c -o $@ $<
    ifeq ($(CIFLAG), 1)
        $(CC) $(CFLAGS) -E -P $< -o $(OUT_DIR)/$<.preproc
        $(CC) $(CFLAGS) -E -dD $< -o $(OUT_DIR)/$<.macros
    endif

I'm sure I can include a different file based on the CIFLAG value, but was hoping I could do it by modifying the pattern rule.

Any ideas?

Thanks!

I did as MadScientist suggested (thanks for the education) but don't get what I want. My file now appears as:

$(OUT_DIR)/%.0: %.c
    $(CC) $(CFLAGS) -c -o $@ $<
    [ $(CI_BUILD) -eq 0 ] \
        || {$(CC) $(CFLAGS) -E -P $< -o $(OUT_DIR)/$<.preproc \
        && $(CC) $(CFLAGS) -E -dD $< -o $(OUT_DIR)/$<.macros; }

But, when I execute, I get this (lots of irrelevant output trimmed):

cc -c -o test.o
[ 1 -eq 0 ] \
     || {cc -E -P test.c -o test.c.preproc \
     && cc -E -dD test.c -o test.c.macros; }

/bin/sh: -c: line 2: syntax error near unexpected token '}'

Is the ';' a problem?

You cannot use make conditionals like ifeq in the recipe passed to the shell, because the shell runs the recipe not make. You can use shell conditionals:

$(OUT_DIR)/%.0: %.c
        $(CC) $(CFLAGS) -c -o $@ $<
        [ ($(CIFLAG) -ne 1 ] \
          || { $(CC) $(CFLAGS) -E -P $< -o $(OUT_DIR)/$<.preproc \
               && $(CC) $(CFLAGS) -E -dD $< -o $(OUT_DIR)/$<.macros; }

Of course, you haven't discussed how you plan to set the CIFLAG variable for some targets but not others...

I was able to make it work by changing the code to:

$(OUT_DIR)/%.0: %.c
    $(CC) $(CFLAGS) -c -o $@ $<
    if [ ($(CIFLAG) -ne 1 ]; then \
      $(CC) $(CFLAGS) -E -P $< -o $(OUT_DIR)/$<.preproc; \
      $(CC) $(CFLAGS) -E -dD $< -o $(OUT_DIR)/$<.macros; fi

You mustn't indent the Make conditional with tabs:

$(OUT_DIR)/%.0: %.c
    $(CC) $(CFLAGS) -c -o $@ $<
ifeq ($(CIFLAG), 1)
    $(CC) $(CFLAGS) -E -P $< -o $(OUT_DIR)/$<.preproc
    $(CC) $(CFLAGS) -E -dD $< -o $(OUT_DIR)/$<.macros
endif

See bullet 4: https://www.gnu.org/software/make/manual/html_node/Recipe-Syntax.html

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