如何使用源文件夹创建makefile?

时间:2013-01-15 03:31:08

标签: makefile

我想创建一个带有PATH参数的模块化makefile,但我无法弄清楚如何。

这就是我之前所拥有的:

CC=
CFLAGS=-c -stack-protect
LDFLAGS=
SOURCES=
SSOURCES=
OBJECTS=$(SOURCES:.cpp=.o)
SOBJECTS=$(SSOURCES:.s=.o)
DEBUGFLAGS=-g -DDEBUG
EXECUTABLE=

all: CC += -DNDEBUG
all: $(SOURCES) $(SSOURCES) $(EXECUTABLE)

$(EXECUTABLE): $(OBJECTS) $(SOBJECTS)
        $(CC) $(LDFLAGS) $(OBJECTS) $(SOBJECTS) -o $@

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

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

debug: CFLAGS += $(DEBUGFLAGS)
debug: $(SOURCES) $(SSOURCES) $(LDFLAGS) $(EXECUTABLE)
        $(CC) $(LDFLAGS) $(OBJECTS) $(SOBJECTS) -o $(EXECUTABLE)

clean:
        rm -rf *o $(OBJECTS) $(SOBJECTS)

这就是我要做的或多或少的事情:

PATH=
CC=
CFLAGS=-c -stack-protect
LDFLAGS=
SOURCES=./src1 ./src1
SSOURCES=./src1 ./src2
FSOURCES=$(SOURCES:./=$(PATH))
FSSOURCES=$(SSOURCES:./=$(PATH))
OBJECTS=$(SOURCES:.cpp=.o)
SOBJECTS=$(SSOURCES:.s=.o)
DEBUGFLAGS=-g -DDEBUG
EXECUTABLE=

all: CC += -DNDEBUG
all: $(FSOURCES) $(FSSOURCES) $(EXECUTABLE)

$(EXECUTABLE): $(OBJECTS) $(SOBJECTS)
        $(CC) $(LDFLAGS) $(OBJECTS) $(SOBJECTS) -o $@

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

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

debug: CFLAGS += $(DEBUGFLAGS)
debug: $(FSOURCES) $(FSSOURCES) $(LDFLAGS) $(EXECUTABLE)
        $(CC) $(LDFLAGS) $(OBJECTS) $(SOBJECTS) -o $(EXECUTABLE)

clean:
        rm -rf *o $(OBJECTS) $(SOBJECTS)

我该如何做到这一点?

1 个答案:

答案 0 :(得分:0)

我假设您要制作的文件所在的文件位于文件夹src2中,而您要构建,创建和执行的文件位于文件夹src1中。

VPATH = src1:src2:objects:include:libs

CFLAGS= -I ./include -Wall -g -stack-protect

LDFLAGS = -lstdc++
# You can append more libs as required.

CC = gcc


target: $(patsubst ./src1/%.c,./objects/%.o,$(wildcard ./src1/*.c)) ./libs/libmylib.so  
    $(CC) $(patsubst ./src/%.c,./obj_dbg/%.o,$(wildcard ./src/*.c)) $(LDFLAGS) -L ./libs -lmylib -o target

./objects/%.o: ./src/%.c ./include/*.h 
    @mkdir -p ./objects
    $(CC) $(CFLAGS) -c $< -o $@

./libs/libmylib.so: ./src2/%.c ./include/*.h 
    @mkdir -p ./libs
    $(CC) $(CFLAGS) -c $< -o $@ 

对于makefile教程,您可以查看以下链接。 http://www.tune2wizard.com/linux-makefiles/