2011-10-12 67 views
1

我的makefile目標:更新時傳遞的變量改變

ifndef VEC_LEN 
     VEC_LEN = 1 
endif 

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

有沒有辦法告訴做出my_target應更新時VEC_LEN 改變

更新:

我的腳本現在這個樣子(和他們的工作): 的Makefile

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 

輸出示例:

[email protected]:~$ make 
echo "Updated!" 
Updated! 
touch answer 
[email protected]:~$ make 
make: `answer' is up to date. 
[email protected]:~$ make ANSWERTOLIFETHEUNIVERSEANDEVERYTHING=3 
echo "Updated!" 
Updated! 
touch answer 
[email protected]:~$ make ANSWERTOLIFETHEUNIVERSEANDEVERYTHING=3 
make: `answer' is up to date. 
+0

更改時間?在建立其他目標?自從上次運行Make?你能給個例子嗎? – Beta

+0

@Beta我有一個bash腳本,多次構建我的目標進行基準測試,通常使用不同的VEC_LEN。所以如果我打電話「make; make」,那麼my_target只能被構建一次。對於「make; make VEC_LEN = 10」,應該使用VEC_LEN = 1和VEC_LEN = 10來構建。 –

+0

Duplicate:http://stackoverflow.com/questions/3236145/force-gnu-make-to-rebuild-objects-affected-by-compiler-definition – slowdog

回答

1

假設語言C, 我認爲最簡單的方法可能是:

  1. 準備vec_len.h具有線#define VEC_LEN 1
  2. 交流再添#include "vec_len.h"
  3. 如果VEC_LEN的價值有重寫vec_len.h
  4. 使用通常的.c構建文件和頭文件依賴項

編輯
雖然這是一個有點天真的方式,做你的 的情況下改變工作?

準備一個腳本(define.sh)像下面這樣:

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

,並在生成文件的開頭添加以下行:

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

是的,這是沒有問題的。只要它有效。我現在嘗試在makefile的開頭運行一個bash腳本,它在必要時更新頭文件,但是我找不到在makefile開頭運行簡單的bash命令的任何方法。 –

+0

嗯,我看...然後請看看編輯。 –

+0

非常感謝!這工作。我在問題中添加了我的代碼。我實際上嘗試過類似的東西,但是使用=而不是:=,所以bash腳本從未執行過。 –

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 
+0

有趣。你能給我一個關於如何使用它的提示嗎?當我運行make時,它告訴我目標沒有任何事情要做。當我將«OLD_VEC_LEN = 1»放入手動創建的old_vec_len並運行«make VEC_LEN = 2»時,我會得到相同的輸出。 –

+0

@ SimonA.Eugster:真的嗎? 「沒有事情要做」意味着Make不知道該目標的規則。 makefile中的目標名稱和命令中的目標名稱('make target')是否可能不完全一致? – Beta

+0

啊。問題找到。你是對的:當我從上面複製/粘貼makefile時,我得到四個空格用於縮進。如果我將它們替換爲製表符,它將起作用!非常好。 –