【问题标题】:GCC: link error while linking files from parent directoryGCC:从父目录链接文件时出现链接错误
【发布时间】:2021-05-07 10:25:15
【问题描述】:

在包含父目录中的 C 文件时出现链接错误。感谢任何帮助或提示。

hashcons_test.c 导入

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

#include "stdbool.h"
#include "stdio.h"
#include "stdlib.h"

生成文件

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中定义的函数

【问题讨论】:

    标签: c gcc makefile


    【解决方案1】:

    您永远不会将hashcons.o 链接到output。由于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 在预处理器阶段完全解决,在链接过程中不考虑。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-10-27
      • 2010-12-28
      • 2012-06-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-11
      相关资源
      最近更新 更多