我有一个包含以下文件的项目,所有项目都在同一个文件夹中
client.c
server.c
reliable_udp.h
reliable_udp.c
conf.h
在其他库中,client.c
还包括reliable_udp.h
(#include "reliable_udp.h"
),以便使用packet_send
和print_conf
函数(在reliable_udp.c
中实现{1}})。
我是Makefile
的新手,我试图写一个:
CC = gcc
CFLAGS = -Wall -Wextra -Wpedantic -O3
SRC = client.c server.c
OBJ = $(SRC:.c=.o)
all: $(OBJ)
${CC} ${CLFAGS} client.o -o client
${CC} ${CLFAGS} server.o -o server
client.o: reliable_udp.h
clean:
rm -f *.o core
cleanall:
rm -f *.o core client server
如果我尝试运行make
,我会得到以下输出:
gcc -Wall -Wextra -Wpedantic -O3 -c -o client.o client.c
gcc client.o -o client
client.o: In function `main':
client.c:(.text.startup+0x84): undefined reference to `packet_send'
client.c:(.text.startup+0x8b): undefined reference to `print_conf'
collect2: error: ld returned 1 exit status
Makefile:7: recipe for target 'all' failed
make: *** [all] Error 1
显然我没有正确地写Makefile
。我该如何解决? 为什么我收到此错误?
答案 0 :(得分:1)
快速解决方法是修改Makefile,如下所示:
all: $(OBJ)
${CC} ${CLFAGS} reliable_udp.o client.o -o client
${CC} ${CLFAGS} reliable_udp.o server.o -o server
它并不漂亮,在现实世界中#34;一个更好的选择可能是为" reliable_udp"创建一个共享库,或者至少重构一下Makefile。
错误的原因是" reliable_udp"未编译到最终的二进制文件中,因为它未在makefile中的任何位置显式指定。
答案 1 :(得分:1)
为什么我收到此错误?
因为链接配方不包含'reliable_udp.0'对象,并且因为makefile中的任何内容都不会将'reliable_udp.c'编译为'reliable_udp.o`
发布的makefile包含几个问题,如问题评论中所述。
以下是一个提议的简单makefile,它应该执行所需的功能。
注意:将<tab>
替换为制表符
注意:在以下makefile中,调用命令可以是:
make -- to generate both 'client' and 'server'
as it will use the first target, which is 'all'
make all -- to generate both 'client' and 'server'
make client -- to only generate the 'client' executable
make server -- to only generate the 'server' executable
make clean -- to delete the object files
make cleanall -- to delete the object files and the executables
现在提出的makefile
#use ':=' rather than '=' so macros only evaluated once
#assure the desired utilities are used
CC := /usr/bin/gcc
RM := /usr/bin/rm -f
CFLAGS := -Wall -Wextra -Wpedantic -std=GNU11 -O3
#generate a list of all the source files
SRC := client.c server.c reliable_udp.c
#generate a list of all the object file names
OBJ := $(SRC:.c=.o)
#let make know that the target 'all' will not produce a file of the same name
#notice the 'all' target dependencies are the final executables
.PHONY: all
all: client server
#this will perform all the compiles
#while expecting the user supplied header files to be in the local directory
%.o:%.c
<tab>$(CC) -c $(CFLAGS) $^ -o $@ -I.
#link the 'client' executable
client: client.o reliable_udp.o
<tab>${CC} $^ -o $@
#link the 'server' executable
server: server.o reliable_udp.o
<tab>${CC} $^ -o $@
#let make know that this target will not produce a file of the same name
.PHONY: clean
clean:
<tab>$(RM) $(OBJ) core
#let make know that this target will not produce a file of the same name
.PHONY: cleanall
cleanall:
<tab>$(RM) $(OBJ) core client server