编译并将包含目标文件的源文件链接到另一个数据结构

时间:2016-08-24 02:00:57

标签: c makefile

这是我目前的Makefile:

CC=gcc
INCLUDE=./Structures/
CFLAGS=-Wall -I$(INCLUDE)
OBJS=rlmain.o rlist.o queue.o

.PHONY: all clean

all: rlmain

queue.o: $(INCLUDE)queue.c $(INCLUDE)queue.h
        $(CC) $(CFLAGS) -c $(INCLUDE)queue.c -o queue.o

rlist.o: $(INCLUDE)rlist.c $(INCLUDE)rlist.h
        $(CC) $(CFLAGS) -c $(INCLUDE)rlist.c -o rlist.o

rlmain: main.c rlist.o queue.o
        $(CC) $(CFLAGS) main.c rlist.o queue.o -o rlmain

clean: 
        rm -f *.o rlmain

Makefile位于顶级目录中。在名为“Structures”的下层目录中是我的数据结构的文件集合。我的数据结构实现了一个就绪列表 - 一个链接的队列列表。

我设法让queue.o使用'-c'工作,但我无法获得rlist.o,因为rlist.c不包含main方法,它必须链接到queue.o函数。我正在使用命令make

除命令外的所有其他工作。我想编写一个命令来告诉编译器将queue.o函数链接到rlist.c编译但不编译需要main()的函数。我该怎么做才能实现这一目标?

1 个答案:

答案 0 :(得分:1)

Note: `<tab>` needs to be replaced with a tab character
Note: use `:=` when defining macros, so they are only evaluated once

# select the specific external executables to run
CC := /usr/bin/gcc
RM := /usr/bin/rm

INCLUDE := ./Structures/
CFLAGS  := -c -Wall -Wextra -pedantic -Wconversion -std=gnu99 
OBJS    := main.o rlist.o queue.o

.PHONY: all clean

all: rlmain

queue.o: $(INCLUDE)queue.c $(INCS)
<tab>$(CC) $(CFLAGS) $< -o $@ -I$(INCLUDE)

rlist.o: $(INCLUDE)rlist.c $(INCS)
<tab>$(CC) $(CFLAGS) $< -o $@ -I$(INCLUDE)

main.o: $(INCLUDE)main.c $(INCS)
<tab>$(CC) $(CFLAGS) $< -o $@ -I$(INCLUDE)

rlmain: $(OBJS) 
<tab>$(CC) $(OBJS) $(LFLAGS)

clean: 
<tab>$(RM) -f *.o rlmain

- 编辑 - 添加后 - 以下是一些比较常见的GNU make实用程序宏

$@  <<-- the name to the left of the colon on the `rule`

    The file name of the target.
$%

    The target member name, when the target is an archive member.
$<  <<-- I use this to reference the first dependency on the `rule`

    The name of the first prerequisite.
$?  <<-- a more reliable method to reference the first dependency on the `rule`

    The names of all the prerequisites that are newer than the target, with spaces between them. For prerequisites which are archive members, only the named member is used (see Archives).
$^
$+

    The names of all the prerequisites, with spaces between them. For prerequisites which are archive members, only the named member is used (see Archives). The value of $^ omits duplicate prerequisites, while $+ retains them and preserves their order.
$*

    The stem with which an implicit rule matches (see How Patterns Match).
$(@D)
$(@F)

    The directory part and the file-within-directory part of $@.
$(*D)
$(*F)

    The directory part and the file-within-directory part of $*.
$(%D)
$(%F)

    The directory part and the file-within-directory part of $%.
$(<D)
$(<F)

    The directory part and the file-within-directory part of $<.
$(^D)
$(^F)

    The directory part and the file-within-directory part of $^.
$(+D)
$(+F)

    The directory part and the file-within-directory part of $+.
$(?D)
$(?F)

    The directory part and the file-within-directory part of $?.