gpt4 book ai didi

c - Makefile 链接到一个库

转载 作者:太空宇宙 更新时间:2023-11-04 08:23:53 25 4
gpt4 key购买 nike

我有以下生成文件。我在路径/usr/local/lib 中有共享库 lcustom。我在我的程序 test.y 中使用该库中的函数,但它为 libcustom.so 中定义的函数提供了 undefined reference 。下面的 makefile 有什么问题.

all: test


test.tab.c test.tab.h: test.y
bison -d test.y

lex.yy.c: test.l test.tab.h
flex test.l

test: lex.yy.c test.tab.c test.tab.h test_util.c
gcc -lcustom -o test test.tab.c test_util.c lex.yy.c

clean:
rm test test.tab.c lex.yy.c test.tab.h

最佳答案

已经很久没有认真写过makefile了,如有错误请指出。

有一些方法可以通过使用隐式规则来避免遇到此类问题:

.PHONY: all clean

LDFLAGS=-lcustom
CFLAGS= # your gcc options start here

all: test

test.tab.c test.tab.h: test.y
bison -d test.y

lex.yy.c: test.l test.tab.h
flex test.l

lex.yy.o: lex.yy.c

tast.tab.o: test.tab.c test.tab.h

test_util.o: test_util.c

test: lex.yy.o test.tab.o test_util.o

clean:
rm -f test test.tab.c lex.yy.c test.tab.h *.o

然后你就避免了所有痛苦的事情。

一般来说,最好显式生成.o文件,然后使用链接器来处理它们,这样如果构建失败,你就会明确知道它出了什么问题,特别是编译时错误,或链接器错误。

关于你的问题的原因,我认为你应该把 -lcustom 放在正确的位置才能使它起作用。我很少看到有人将 -l 标志放在 gcc 之后,所以我很确定这是不正确的。我猜你应该把它放在最后。

PS:在我的评论中,nm 是一个列出目标文件中符号的工具。具体来说,在您的输出中,T 表示函数在文本段中并且已导出,因此应该能够链接。查看 man nm 了解更多信息。

关于c - Makefile 链接到一个库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31867586/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com