对如何创建Makefile感到困惑

时间:2018-03-25 22:22:17

标签: makefile

我正在尝试创建一个Makefile而且我有点卡住了。

到目前为止,我一直在编译我的3个文件(2个标题和1个主程序):

gcc -c phypages.c -o phypages.o
gcc -c pagetable.c -o pagetable.o
gcc -c analysis.c -o analysis.o
gcc analysis.o phypages.o pagetable.o -o analysis

我想制作一个Makefile来帮助我解决这个问题。当我在没有Makefile的情况下编译和链接文件时,一切正常,但是当我尝试制作Makefile时,我得到了一堆错误。你能给我一些关于如何制作基本Makefile的技巧吗?

1 个答案:

答案 0 :(得分:0)

这是一个好的开始:

# Binary name
NAME    = analysis

# Compiler settings
CC      = gcc
CFLAGS  += -Wall -Wextra
CFLAGS  += -Werror

# Source files
SRCS    = phypages.c        \
          pagetable.c       \
          analysis.c

# Object files
OBJS    = $(SRCS:.c=.o)

RM  = rm -f


# Default rule, it should call all your rules that create
# an executable, or build a library...
# Here, it calls only the $(NAME) rule, that builds `analysis`
all: $(NAME)

# Rule to build your object files and link them into a binary
$(NAME): $(OBJS)
    $(CC) -o $(NAME) $(OBJS)

# Rule to remove object files
clean:
    $(RM) $(OBJS)

# Rule to remove binary, calls the 'clean' rule first
fclean: clean
    $(RM) $(NAME)

# Rule to remove object files and binary, then re-build everything
re: fclean all

# Rules that are not linked with a filename should be listed here
.PHONY: all clean fclean re

然后,您可以运行make analysis或仅make来构建您的程序。

下次更改文件时,再次运行make,只会重新编译您更改的文件,而不是整个项目。