Makefileメモ

Makefile Tutorial By Exampleから抜粋。課題やレポートで少しずつ日常的に使う機会を持つ。

String Substitution

foo := a.o b.o l.a c.o
one := $(patsubst %.o,%.c,$(foo))

# This is a shorthand for the above
two := $(foo:%.o=%.c)
# This is the suffix-only shorthand, and is also equivalent to the above.
three := $(foo:.o=.c)

all:
	echo $(one)
	echo $(two)
	echo $(three)

Multiline

The backslash (“") character gives us the ability to use multiple lines when the commands are too long

some_file: 
	echo This line is too long, so \
		it is broken up into multiple lines

* Wildcard

I suggest that you always wrap it in the wildcard function, because otherwise you may fall into a common pitfall described below.

# Print out file information about every .c file
print: $(wildcard *.c)
	ls -la  $?

* may be used in the target, prerequisites, or in the wildcard function.

Danger: * may not be directly used in a variable definitions

Danger: When * matches no files, it is left as it is (unless run in the wildcard function)

thing_wrong := *.o # Don't do this! '*' will not get expanded
thing_right := $(wildcard *.o)

all: one two three four

# Fails, because $(thing_wrong) is the string "*.o"
one: $(thing_wrong)

# Stays as *.o if there are no files that match this pattern :(
two: *.o 

# Works as you would expect! In this case, it does nothing.
three: $(thing_right)

# Same as rule three
four: $(wildcard *.o)

Backlinks

There are no notes linking to this note.