In function `_start‘: (.text+0x20): undefined reference to `main‘

出现的错误:

/usr/lib/gcc/x86_64-linux-gnu/7/../../../x86_64-linux-gnu/Scrt1.o: In function `_start':
(.text+0x20): undefined reference to `main'
collect2: error: ld returned 1 exit status
Makefile:2: recipe for target 'all' failed
make: *** [all] Error 1

Background:

Test Makefile grammer

FIles:

├── main.c
├── Makefile
├── study.c
├── study.h
├── visit.c
├── visit.h

Makefile:

all:     visit.o study.o
        gcc main.o visit.o study.o -o zhs
visit.o: visit.c
        gcc -c visit.c -o visit.o
study.o: study.c
        gcc -c study.c -o study.o

clean:
        rm *.o

Result:

$ make 
gcc visit.o study.o -o zhs
/usr/lib/gcc/x86_64-linux-gnu/7/../../../x86_64-linux-gnu/Scrt1.o: In function `_start':
(.text+0x20): undefined reference to `main'
collect2: error: ld returned 1 exit status
Makefile:2: recipe for target 'all' failed
make: *** [all] Error 1

Resolve:

Missed the compile of main.c. The executable file relies on main.o. New Makefile:

all:    main.o visit.o study.o
        gcc main.o visit.o study.o -o zhs
main.o: main.c
        gcc -c main.c -o main.o
visit.o: visit.c
        gcc -c visit.c -o visit.o
study.o: study.c
        gcc -c study.c -o study.o

clean:
        rm *.o

 Optimized Makefile:

CC=gcc
OBJECTS=main.o study.o visit.o
TARGET=all
$(TARGET): $(OBJECTS)
        $(CC) $^ -o zhs

main.o: main.c
        $(CC) -c $< -o $@
visit.o: visit.c
        $(CC) -c $< -o $@
study.o: study.c
        $(CC) -c $< -o $@

clean:
        rm *.o

Explanation:

  1. Define varaibles: compiler(gcc), Objects(main.o, study.o, visit.o)
  2. TARGET relies on all OBEJECTS.
  3. $^: A list of all depend files
  4. $<: The file name of the first depend file
  5. $@: Name of the taret

Further optimized Makefile:

CC=gcc
TARGET=all
OBJECTS=main.o study.o visit.o
$(TARGET): $(OBJECTS)
        $(CC) $^ -o zhs
*.o: *.c
        $(CC) *.c $< -o $@

clean:
        rm *.o

Result:

├── main.c
├── main.o
├── Makefile
├── study.c
├── study.h
├── study.o
├── visit.c
├── visit.h
├── visit.o
└── zhs

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值