制作文件,看起来好吗?

时间:2011-03-25 13:12:54

标签: c

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文件)

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

我不得不添加-std = c99,因为我对循环错误感到有些奇怪,但仍然不明白为什么我需要将matrix.o放在行中..

3 个答案:

答案 0 :(得分:5)

文件正常。它不易维护。

这个网站有一个关于如何制作漂亮的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 $@

.cpp.o:
    $(CC) $(CFLAGS) $< -o $@

这应该向您展示如何增强可维护性(将额外文件添加到SOURCES,其余文件自动完成。

答案 1 :(得分:1)

以下文件支持make all make 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
# $@ is the file we're making, aka matrix-mul
$(TARGET): $(OBJECTS)
    $(LD) -o $@ $(OBJECTS) $(LDFLAGS)

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

# 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文件构建TARGET。

答案 2 :(得分:0)

我在此强烈建议的一件事是添加一个clean目标,删除所有中间文件(可能是所有.o文件),如下所示:

clean:
    rm *.o

要获得额外的功劳,请将所有*.o个文件放入make变量中,并将该变量用作运行规则的目标,并在上面的rm命令后使用。

我希望您这样做的原因是出于调试目的。它可能你上面的规则之一是错误的,但是既然你已经构建了所有.o个文件,那么它每次只会拾取一个旧文件。如果你在构建之前做了make clean,它就会抓住它。

相关问题