使用makefile的subst写一个makefile看看
时间: 2023-11-06 21:07:13 浏览: 39
以下是使用makefile的subst写的一个简单的makefile示例:
```
CC = gcc
CFLAGS = -Wall -Wextra
SOURCES = main.c
OBJECTS = $(subst .c,.o,$(SOURCES))
EXECUTABLE = myprogram
all: $(EXECUTABLE)
$(EXECUTABLE): $(OBJECTS)
$(CC) $(CFLAGS) $(OBJECTS) -o $(EXECUTABLE)
$(OBJECTS): $(SOURCES)
$(CC) $(CFLAGS) -c $(subst .o,.c,$@) -o $@
clean:
rm -f $(OBJECTS) $(EXECUTABLE)
```
在上面的示例中,我们使用了`subst`函数将`.c`替换为`.o`来生成目标文件列表。我们还使用`subst`函数将目标文件名转换为源文件名,以便编译器可以找到正确的源文件来编译。
相关问题
usage of $(subst) in makefile?
The `$(subst)` function in Makefile is used to replace all occurrences of a string with another string in a given variable or text. The syntax for using the `$(subst)` function is as follows:
```
$(subst from,to,text)
```
Here, `from` is the string to be replaced, `to` is the replacement string, and `text` is the variable or text in which the replacement should be made.
For example, suppose we have a variable `message` with the value `Hello, world!`. If we want to replace all occurrences of the string `world` with the string `everyone`, we can use the `$(subst)` function like so:
```
new_message = $(subst world,everyone,$(message))
```
This will replace all occurrences of the string `world` with the string `everyone` in the `message` variable, and store the result in the `new_message` variable.
So, in this example, `new_message` would have the value `Hello, everyone!`.
The `$(subst)` function can be very useful in Makefiles when we need to perform string replacements on variable values or text.
makefile函数使用
Makefile中的函数可以在变量和规则中使用。下面是一些常用的Makefile函数:
- $(subst from,to,text):将text中的from替换成to。
- $(patsubst pattern,replacement,text):在text中查找符合pattern的字符串,并将其替换成replacement。
- $(strip string):删除string中的前导和尾随空格。
- $(shell command):执行shell命令并返回结果。
- $(wildcard pattern):返回符合pattern的所有文件名。
- $(foreach var,list,text):将list中的每个元素赋值给变量var,并将text中的变量替换成当前元素的值。
下面是一个例子:
```
SOURCES := $(wildcard *.c)
OBJECTS := $(patsubst %.c,%.o,$(SOURCES))
.PHONY: all clean
all: program
program: $(OBJECTS)
gcc -o $@ $^
%.o: %.c
gcc -c $< -o $@
clean:
rm -f program $(OBJECTS)
```
在这个例子中,wildcard函数用于获取所有的.c文件,patsubst函数用于将.c文件替换成.o文件,foreach函数用于遍历所有的.o文件。同时,我们还使用了shell命令来执行编译器。