c - (.text+0x20) : undefined reference to `main' and undefined reference to function

标签 c gcc compilation compiler-errors makefile

我在让我的 makefile 正常工作时遇到问题。我遇到的第一个问题是对 main 的 undefined reference 。我的 producer.c 文件中有 main 作为函数。第二个问题是对 SearchCustomer() 的 undefined reference 。

错误:

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

最佳答案

这条规则

main: producer.o consumer.o AddRemove.o
   $(COMPILER) -pthread $(CCFLAGS) -o producer.o consumer.o AddRemove.o

错了。它说要创建一个名为 producer.o 的文件(使用 -o producer.o),但您想要创建一个名为 main 的文件。请原谅大喊大叫,但始终使用 $@ 来引用目标:

main: producer.o consumer.o AddRemove.o
   $(COMPILER) -pthread $(CCFLAGS) -o $@ producer.o consumer.o AddRemove.o

正如 Shahbaz 正确指出的那样,gmake 专业人员也会使用 $^,它扩展到规则中的所有先决条件。一般来说,如果您发现自己重复了一个字符串或名称,那么您做错了,应该使用一个变量,无论是内置变量还是您创建的变量。

main: producer.o consumer.o AddRemove.o
   $(COMPILER) -pthread $(CCFLAGS) -o $@ $^

关于c - (.text+0x20) : undefined reference to `main' and undefined reference to function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20514587/

相关文章:

c++ - MinGW gcc C 编译器工作,但 g++ 不工作

c++ - 静态编译 libc++

java - : binary,解释、执行、编译这几个概念之间有什么关系?

c - 函数返回垃圾值

c++ - 基于 GCC 构建的 Clang

c - 不带缓冲区的读写系统调用

c++ - 如何摆脱不安全的功能(sprintf,...)

java - 将 .xsl 文件编译为 .class 文件

c - 解释gdb段错误

c - 差异固定宽度字符串和零终止字符串