开发者

Makefile: return first two characters of a string

开发者 https://www.devze.com 2023-03-29 01:26 出处:网络
Given a string in a Makefile, is it possible to ex开发者_开发技巧tract the first two characters of an unknown string using Makefile syntax (without using shell calls)?

Given a string in a Makefile, is it possible to ex开发者_开发技巧tract the first two characters of an unknown string using Makefile syntax (without using shell calls)?

for instance,

VAR := UnKnown
VAR_TERSE = $(call get_first_two_chars, $(VAR))

define get_first_two_char
...
endef


Well, it can be done, but it's pretty messy to implement by hand. The easiest thing to do is to get the GNU Make Standard Library, which has a built-in substr function. If that's overkill, you can extract just that function from the library, but like I said, it's surprisingly messy.

Essentially you do a series of substitutions on the string to insert a space after each character:

EMPTY:=
SPACE:=$(EMPTY) $(EMPTY)
VAR := UnKnown
TMP:=$(subst a,a ,$(subst b,b ,$(subst c,c ,.........$(VAR)))))
# TMP now has "U n K n o w n"

Next you can use the $(wordlist) function to grab the first two "words" of the intermediate result:

TMP2:=$(wordlist 1,2,$(TMP))
# TMP2 now has "U n"

Finally, you use $(subst) again, now to strip out the space that you injected originally:

VAR_TERSE := $(subst $(SPACE),,$(TMP2))
# VAR_TERSE now has "Un"


I really don't approve of forcing Make to do things it clearly doesn't want to do, but... I can't resist a good puzzle.

$(eval FOO := $$$(VAR))
$(eval FOO := $$$(FOO))
VAR_TERSE:= $(VAR:$(FOO)=)


Use the shell and sed?

define get_first_two_char
$(shell echo $1 | sed 's/^\(..\).*/\1/' )
endef
0

精彩评论

暂无评论...
验证码 换一张
取 消