C语言 GCC:从父目录链接文件时出现链接错误



我得到一个链接错误,而包括从父目录的C文件。谢谢你的帮助和提示。

hashcons_test.cimports

#include "hashcons.h"   // I have tried "../hashcons.h" but no success 
#include "stdbool.h"
#include "stdio.h"
#include "stdlib.h"

Makefile

CC=gcc 
CFLAGS=-I ..
all: output test clean
output: driver.o
$(CC) $(CFLAGS) hashcons_test.o driver.o -o output
prime.o: ../prime.h ../prime.c
$(CC) -c $(CFLAGS) ../prime.c -o ../prime.o
hashcons.o: prime.o ../hashcons.h ../hashcons.c
$(CC) -c $(CFLAGS) ../hashcons.h -o ../hashcons.o
hashcons_test.o: hashcons.o hashcons_test.c
$(CC) -c $(CFLAGS) hashcons_test.c
driver.o: hashcons_test.o
$(CC) -c $(CFLAGS) driver.c -o driver.o
test: output
@./output
clean:
@rm -rf *.o output

目录
.
├── hashcons.c
├── hashcons.h
├── prime.c
├── prime.h
└── tests
├── Makefile
├── driver.c
├── driver.o
├── hashcons_test.c
└── hashcons_test.o

错误:

gcc  -c -I .. ../prime.c -o ../prime.o
gcc  -c -I .. ../hashcons.h -o ../hashcons.o
gcc  -c -I .. hashcons_test.c
gcc  -c -I .. driver.c -o driver.o
gcc  -I .. hashcons_test.o driver.o -o output
Undefined symbols for architecture x86_64:
"_hash_cons_get", referenced from:
_new_hash_cons_integer in hashcons_test.o
_new_hash_cons_integer in driver.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
make: *** [output] Error 1

hash_cons_gethascons.h

中定义的函数

永远不要把hashcons.ooutput联系起来。由于hashcons_test.odriver.o都不包含必要的符号,因此会出现链接器错误。你需要调整output:

的规则
output: driver.o
$(CC) $(CFLAGS) hashcons_test.o hashcons.o driver.o -o output
#                                   ^^^^^^^^^^

但是,您应该更进一步,正确列出所有依赖项,并使用$^(用于所有依赖项):

output: driver.o hashcons_test.o hashcons.o
$(CC) $(CFLAGS) $^ -o $@

注意,这与您的#includes没有关系。#includes在预处理器阶段被完全解决,在链接过程中不被考虑。