出现的错误:
/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:
- Define varaibles: compiler(gcc), Objects(main.o, study.o, visit.o)
- TARGET relies on all OBEJECTS.
- $^: A list of all depend files
- $<: The file name of the first depend file
- $@: 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