我遇到问题让我的makefile无错误地工作。我遇到的第一个问题是对main的未定义引用。我作为一个函数在我的producer.c文件中有main。第二个问题是对SearchCustomer()的未定义引用。
错误:
bash-4.1$ make
gcc -Wall -c producer.c shared.h
gcc -Wall -c consumer.c shared.h
gcc -Wall -c AddRemove.c shared.h
gcc -pthread -Wall -o producer.o consumer.o AddRemove.o
/usr/lib/gcc/x86_64-redhat-linux/4.4.7/../../../../lib64/crt1.o: In function `_start':
(.text+0x20): undefined reference to `main'
AddRemove.o: In function `AddRemove':
AddRemove.c:(.text+0xb1): undefined reference to `SearchCustomer'
AddRemove.c:(.text+0x1e9): undefined reference to `SearchCustomer'
AddRemove.c:(.text+0x351): undefined reference to `SearchCustomer'
collect2: ld returned 1 exit status
make: *** [producer] Error 1
生成文件:
COMPILER = gcc
CCFLAGS = -Wall
all: main
debug:
make DEBUG=TRUE
main: producer.o consumer.o AddRemove.o
$(COMPILER) -pthread $(CCFLAGS) -o producer.o consumer.o AddRemove.o
producer.o: producer.c shared.h
$(COMPILER) $(CCFLAGS) -c producer.c shared.h
consumer.o: consumer.c shared.h
$(COMPILER) $(CCFLAGS) -c consumer.c shared.h
AddRemove.o: AddRemove.c shared.h
$(COMPILER) $(CCFLAGS) -c AddRemove.c shared.h
ifeq ($(DEBUG), TRUE)
CCFLAGS += -g
endif
clean:
rm -f *.o
答案 0 :(得分:14)
此规则
main: producer.o consumer.o AddRemove.o
$(COMPILER) -pthread $(CCFLAGS) -o producer.o consumer.o AddRemove.o
错了。它说创建一个名为producer.o的文件,但是你想创建一个名为main
的文件。请原谅,但总是使用$ @参考目标:
main: producer.o consumer.o AddRemove.o
$(COMPILER) -pthread $(CCFLAGS) -o $@ producer.o consumer.o AddRemove.o
答案 1 :(得分:7)
此错误意味着,在链接时,编译器无法在任何地方找到main()
函数的定义。
在您的makefile中,main
规则将扩展为类似的内容。
main: producer.o consumer.o AddRemove.o
gcc -pthread -Wall -o producer.o consumer.o AddRemove.o
根据gcc
manual page,使用-o
切换如下
-o 文件将输出放在文件文件中。无论生成什么类型的输出,它都适用,无论它是否是可执行文件 文件,目标文件,汇编程序文件或预处理的C代码。如果
中-o
未指定,默认设置是将可执行文件放在a.out
。
这意味着,gcc会将输出放在-o
开关旁边提供的文件名中。因此,此处不是将所有.o
文件链接在一起并创建二进制文件[main
,在您的情况下],而是创建二进制文件producer.o
,链接另一个.o
文件。请更正。