2011-03-25 65 views
1
all: run 

run: test.o list.o matrix.o smatrix.o 
    gcc test.o list.o matrix.o smatrix.o -o matrix-mul 

list.o: list.c list.h 
    gcc -g -c list.c 

matrix.o: matrix.c matrix.h 
    gcc -g -std=c99 -c -o matrix.o matrix.c 

smatrix.o: smatrix.c smatrix.h 
    gcc -g -c -o smatrix.o smatrix.c 

test.o: test.c test.h 
    gcc -g -c test.c 

我在制作makefile时遇到了很多问题,终于得到了这个工作。我只是想确保这些都没问题(不仅仅是为了让程序运行,而且是在一个良好的make文件中)make file,这看起来好吗?

一个问题是,为什么matrix.o和smatrix.o在行中有.o文件gcc -g -c ...其中list.o和test.o没有该行..

我不得不添加-std = c99,因为我对循环错误有些奇怪,不知道为什么我需要把matrix.o放在一行..

+0

我告诉你在这里:http://stackoverflow.com/questions/5432486/make-file-error/5432546#5432546你不需要specyfying输出名称(这是我的错,我把它放在那里)。循环的东西并不奇怪,c90标准不支持在任何地方创建局部变量,比如在for循环头文件中,所以你切换到了c99标准。 – 2011-03-25 13:48:01

+0

是的,我在看到你的改正之前写了这个!谢谢! – codereviewanskquestions 2011-03-25 20:14:13

回答

5

该文件是OK-ISH。这不是很容易维护。

这个网站有关于如何使漂亮的makefile一个很好的教程: http://mrbook.org/blog/tutorials/make/

特别是看看最后一个例子:

CC=g++ 
CFLAGS=-c -Wall 
LDFLAGS= 
SOURCES=main.cpp hello.cpp factorial.cpp 
OBJECTS=$(SOURCES:.cpp=.o) 
EXECUTABLE=hello 

all: $(SOURCES) $(EXECUTABLE) 

$(EXECUTABLE): $(OBJECTS) 
    $(CC) $(LDFLAGS) $(OBJECTS) -o [email protected] 

.cpp.o: 
    $(CC) $(CFLAGS) $< -o [email protected] 

这应该告诉你如何提高维护(添加额外的文件到SOURCES,剩下的就自动完成了

+0

'-Wall' ** **推荐,顺便说一句。 – 2011-03-25 13:28:35

1

以下文件支持make allmake dependmake clean - 您只需要更改第一行。如果您在任何文件中更改包含,请记住make depend

TARGET:=matrix-mul 
SOURCES:=test.c list.c matrix.c smatrix.c 
OBJECTS:=$(SOURCES:%.c=%.o) 
CC=gcc 
CFLAGS=-g -std=c99 -Wall 
LD=gcc 
LDFLAGS= 


# First target - simply say that we want to produce matrix-mul 
all: $(TARGET) 

# To create the target we need all .o files, and we link with LD/LDFLAGS 
# [email protected] is the file we're making, aka matrix-mul 
$(TARGET): $(OBJECTS) 
    $(LD) -o [email protected] $(OBJECTS) $(LDFLAGS) 

#Creating a .o from a .c 
# $< is the c file, [email protected] is the corresponding .o file 
.c.o: 
    $(CC) $(CFLAGS) -c $< -o [email protected] 

# Regenerate dependencies 
depend: 
    $(CC) $(CFLAGS) -MM $(SOURCES) > .depend 

# Remove produced files 
clean: 
    rm -rf $(OBJECTS) $(TARGET) .depend 

# If there's no dependency file, create it 
.depend: depend 

# Include the autogenerated dependency file 
include .depend 

编辑:如果你想要这个更加通用的,可以更换SOURCE:用=行:

SOURCES:=$(wildcard *.c) 

这个Makefile会再简单地从所有的.c文件在当前目录下创建目标。

0

有一件事我会强烈建议这里是添加一个clean目标是删除所有中间文件(可能是所有的.o文件),像这样:

clean: 
    rm *.o 

对于额外的信用,把你所有的*.o文件放在一个make变量中,并将该变量用作运行规则的目标,并在上面的命令后执行。

我希望你这样做的原因是为了调试目的。它可能是你有上面的规则之一错了,但既然你已经建立了所有的.o文件一次,它只是每次都拿起一个旧的。如果你在构建之前做了make clean,它会抓住它。