gcc - 使用 Makefile 编译时缺少 main 函数
问题描述
我正在尝试将源代码编译成二进制文件。
在这两个源文件中,main 函数定义在一个(main.c)中。但是,在将源代码编译为二进制文件时,我仍然收到以下错误。
这是我的Makefile:
CC = gcc
LD = ld
AR = ar
NM = nm
OBJCOPY = objcopy
OBJDUMP = objdump
READELF = readelf
CFLAGS += -Wall -I.
LDADD += -lpthread -ldl -L. -llob
BINARY=test
.PHONY: all
all: $(BINARY)
main.o: main.c
$(CC) $(CFLAGS) -c -o $@ $<
sub.o: sub.c
$(CC) $(CFLAGS) -c -o $@ $<
$(BINARY): sub.o main.o
$(CC) $(CFLAGS) $(LDADD) -o $@ $<
.PHONY: clean
clean:
rm -f $(OBJS) $(BINARY)
这将返回错误:
/usr/lib/gcc/x86_64-linux-gnu/5/../../../x86_64-linux-gnu/crt1.o: In function _start':
(.text+0x20): undefined reference to
main' collect2: error: ld returned 1 exit status
请指教!
解决方案
The error stems from this part
$(BINARY): sub.o main.o
$(CC) $(CFLAGS) $(LDADD) -o $@ $<
The variable $<
refers only to the first dependency, which is sub.o
here. main.o
is hence not linked. The fix is to modify the compile command to
$(CC) $(CFLAGS) $(LDADD) -o $@ $^
where $^
refers to all prerequesites (thanks to @MadScientist for pointing that out). You might also consider storing source and object files in a variable. I'd suggest replacing your rules for compiling sources and linking by the following
SRC = $(wildcard *.c)
OBJ = $(SRC:%.c=%.o)
%.o: %.c
$(CC) $(CFLAGS) -c -o $@ $<
$(BINARY): $(OBJ)
$(CC) $(CFLAGS) $(LDADD) -o $@ $(OBJ)
Here, all .c files in the current directories are compiled into object files and then linked into the executable (adjust the wildcard
line if you don't want every .c file but rather a certain selection).
推荐阅读
- javascript - 图像旋转而不旋转整个对象
- heroku - 当我尝试提交我的机器人时,为什么会出现错误?
- traefik - 如何将带有参数的原始 URI 传递给“查询”中指定的 Traefik ErrorPage 处理程序?
- html - CSS可以隐藏span-element并在悬停时显示它,不适用于p-element
- python - 在 Django 中删除另一个模型中的一行后更新模型
- kubernetes - 正在创建带有 Debian 映像的 Pod,但容器不断崩溃
- r - 在 R 中,按句号拆分文本列并按行映射到相同的 Id
- python-3.x - Kivy - on_press 绑定事件到 btn 不起作用
- python - 如何比较 pandas 中两个 CSV 文件的内容并找出差异?
- docker - 如何正确地将 ssh 密钥文件从 Jenkins 凭据变量传递到 docker build 命令?