首页 > 解决方案 > 使用 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 tomain' collect2: error: ld returned 1 exit status

请指教!

标签: gccmakefile

解决方案


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).


推荐阅读