如何为C创建和运行make文件?

时间:2017-02-21 01:26:41

标签: c makefile

我有3个文件

hellomain.c
hellofunc.c
helloheader.h

我正在通过GCC编译器运行。通常我会输入:

gcc helloheader.h hellomain.c hellofunc.c -o results

一切都会运行。

如何将其转换为makefile?我知道我必须标题makefile。我知道我必须在编译器中键入make来调用它。但不确定实际输入makefile的内容。

2 个答案:

答案 0 :(得分:3)

关于像你这样的项目可能的最简单的makefile:

# The name of the source files
SOURCES = hellomain.c hellofunc.c

# The name of the executable
EXE = results

# Flags for compilation (adding warnings are always good)
CFLAGS = -Wall

# Flags for linking (none for the moment)
LDFLAGS =

# Libraries to link with (none for the moment)
LIBS =

# Use the GCC frontend program when linking
LD = gcc

# This creates a list of object files from the source files
OBJECTS = $(SOURCES:%.c=%.o)

# The first target, this will be the default target if none is specified
# This target tells "make" to make the "all" target
default: all

# Having an "all" target is customary, so one could write "make all"
# It depends on the executable program
all: $(EXE)

# This will link the executable from the object files
$(EXE): $(OBJECTS)
    $(LD) $(LDFLAGS) $(OBJECTS) -o  $(EXE) $(LIBS)

# This is a target that will compiler all needed source files into object files
# We don't need to specify a command or any rules, "make" will handle it automatically
%.o: %.c

# Target to clean up after us
clean:
    -rm -f $(EXE)      # Remove the executable file
    -rm -f $(OBJECTS)  # Remove the object files

# Finally we need to tell "make" what source and header file each object file depends on
hellomain.o: hellomain.c helloheader.h
hellofunc.o: hellofunc.c helloheader.h

可以更简单,但有了这个,你就有了一些灵活性。

为了完整起见,这可能是最简单的makefile:

results: hellomain.c hellofunc.c helloheader.h
    $(CC) hellomain.c hellofunc.c -o results

这基本上就是你在命令行上做的事情。它不是很灵活,如果任何文件发生变化,它将重建所有内容。

答案 1 :(得分:-1)

这是一个带有硬编码文件名的makefile。它很容易理解,但在添加/删除源文件和头文件时更新可能会很繁琐。

results: hellomain.o hellofunc.o
    gcc $^ -o results

hellomain.o: hellomain.c helloheader.h
    gcc -c $<

hellofunc.o: hellofunc.c helloheader.h
    gcc -c $<

确保在makefile中使用制表符来缩进。