How to write a makefile file in Ubuntu?

You can use any text editor to write a Makefile in Ubuntu, here is a common method:

  1. Open the terminal and navigate to your project directory.
  2. Use the command touch Makefile to create a new Makefile file.
  3. Open the Makefile file using a text editor such as vi or nano.
  4. Write rules and commands in the Makefile file.
  5. The format of the rule is: target: dependencies, which means the target file depends on the specified files.
  6. The format of the command is: tab character + command, meaning there is a tab character in front of each command.
  7. Save and close the Makefile file.

Here is a simple example:

# Makefile示例

# 编译器设置
CC = gcc
CFLAGS = -Wall -g

# 目标文件及依赖关系
TARGET = myprogram
OBJS = main.o utils.o

# 默认构建目标
all: $(TARGET)

# 生成目标文件
$(TARGET): $(OBJS)
	$(CC) $(CFLAGS) -o $@ $^

# 生成依赖关系
%.o: %.c
	$(CC) $(CFLAGS) -c -o $@ $<

# 清理生成的文件
clean:
	rm -f $(TARGET) $(OBJS)

To compile the project, type the ‘make’ command in the terminal. For example, type ‘make all’ to compile all target files. Type ‘make clean’ to clean up the generated files.

I hope this simple example can help you get started writing Makefile files in Ubuntu. Please note that Makefile syntax is case-sensitive, so make sure to use uppercase and lowercase letters correctly.

bannerAds