[英]Why while using makefile I receive undefined reference error?
我創建了以下 makefile:
assembler: main.o first_pass.o second_pass.o helpers.o data_array.o symbol_table.o
gcc -Wall -ansi -pedantic main.o first_pass.o second_pass.o helpers.o data_array.o symbol_table.o -o assembler
main.o: main.c header.h
gcc -Wall -ansi -pedantic main.c -o main.o
first_pass.o: first_pass.c header.h
gcc -Wall -ansi -pedantic first_pass.c -o first_pass.o
second_pass.o: second_pass.c header.h
gcc -Wall -ansi -pedantic second_pass.c -o second_pass.o
helpers.o: helpers.c header.h data.h
gcc -Wall -ansi -pedantic helpers.c -o helpers.o
data_array.o: data_array.c header.h data.h
gcc -Wall -ansi -pedantic data_array.c -o data_array.o
symbol_table.o: symbol_table.c header.h data.h
gcc -Wall -ansi -pedantic symbol_table.c -o symbol_table.o
在我的 'main.c' 文件中,我有#include "header.h"
。 在'header.h'中我有所有函數的聲明。 但我收到以下錯誤:
gcc -Wall -ansi -pedantic main.c -o main.o
/tmp/cc3dP7hx.o: In function `main':
main.c:(.text+0x257): undefined reference to `first_pass`
main.c:(.text+0x2e4): undefined reference to `second_pass'
main.c:(.text+0x37f): undefined reference to build_obj_file
main.c:(.text+0x3a9): undefined reference to build_ent_file
main.c:(.text+0x427): undefined reference to free_all_data
main.c:(.text+0x436): undefined reference to free_all_symbols
main.c:(.text+0x44d): undefined reference to free_all_words
collect2: error: ld returned 1 exit status
makefile:4: recipe for target 'main.o' failed
make: *** [main.o] Error 1
問題是您的命令不會創建 object 文件,而是嘗試構建可執行程序:
gcc -Wall -ansi -pedantic main.c -o main.o
您需要-c
選項來創建 object 文件:
gcc -Wall -pedantic main.c -c -o main.o
一個更好的主意是依賴make
隱式規則,這樣您就不必顯式列出所有命令:
CC = gcc
LD = gcc
CFLAGS = -Wall -pedantic
LDFLAGS =
assembler: main.o first_pass.o second_pass.o helpers.o data_array.o symbol_table.o
您可能想要為頭文件依賴項添加規則,或者想辦法自動生成它們(這是可能的)。 除此之外,上面的Makefile
應該足以構建所有 object 文件,然后將它們鏈接到assembler
程序可執行程序中。
請注意,我已經刪除了-ansi
標志,因為它現在大多已經過時了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.