传递的变量更改时更新目标

时间:2011-10-12 11:10:37

标签: makefile

我的makefile:

ifndef VEC_LEN
        VEC_LEN = 1
endif

my_target: a.c
        gcc a.c -DVEC_LEN=$(VEC_LEN)

当VEC_LEN 更改时,有没有办法告诉make my_target应该更新

更新

我的脚本现在看起来像这样(并且它们可以工作): 生成文件

SHELL := /bin/bash

# Define the answer if not defined yet
ANSWERTOLIFETHEUNIVERSEANDEVERYTHING ?= 42

# Update the header file if the answer has changed
# := always executes the shell command, = does not! Quote from http://www.gnu.org/software/make/manual/make.html:
#      immediate = deferred
#      immediate := immediate
DUMMY := $(shell ./updateAnswer.sh $(ANSWERTOLIFETHEUNIVERSEANDEVERYTHING) >logMakefile.txt)

answer : answer.h 
    echo "Updated!"
    touch answer

updateAnswer.sh

#!/bin/bash

# Check if the definition of the answer has changed in the header file
# If yes, re-write it. If not, do not touch it to avoid an updated timestamp.
if grep -q "ANSWER ${1}" answer.h
then
    echo "ANSWER unchanged, is still ${1}."
else
    echo "#define ANSWER ${1}" >answer.h
    echo 'Answer has changed:'
    cat answer.h
fi

示例输出:

simon@x220:~$ make
echo "Updated!"
Updated!
touch answer
simon@x220:~$ make
make: `answer' is up to date.
simon@x220:~$ make ANSWERTOLIFETHEUNIVERSEANDEVERYTHING=3
echo "Updated!"
Updated!
touch answer
simon@x220:~$ make ANSWERTOLIFETHEUNIVERSEANDEVERYTHING=3
make: `answer' is up to date.

2 个答案:

答案 0 :(得分:2)

我认为这将在makefile中执行:

-include old_vec_len

VEC_LEN ?= 1

ifneq ($(VEC_LEN),$(OLD_VEC_LEN))
target: marker
endif

target:
    @echo run_script_to_make_target with VEC_LEN=$(VEC_LEN)

.PHONY:marker
marker:
    @echo OLD_VEC_LEN=$(VEC_LEN) > old_vec_len

答案 1 :(得分:1)

假设语言为C, 我认为最简单的方法可能是:

  1. 准备vec_len.h#define VEC_LEN 1
  2. 在a.c
  3. 中添加#include "vec_len.h"
  4. 如果必须更新VEC_LEN的值,请重写vec_len.h
  5. 使用通常的.c文件和头文件依赖
  6. 进行构建

    修改
    虽然这是一种天真的方式,但以下更改是否适用于您的工作 情况?

    准备一个脚本(define.sh),如下所示:

    #!/usr/bin/bash
    echo '#define VEC_LEN' $1 > vec_len.h
    

    并在makefile的开头添加以下行:

    VEC_LEN ?= 1
    DUMMY := $(shell define.sh $(VEC_LEN))