简体   繁体   English

Makefile链接到库

[英]Makefile linking against a library

I have the following makefile.I have the shared library lcustom in the path /usr/local/lib. 我有以下makefile。/ usr / local / lib路径中有共享库lcustom I am using the functions from that library in my program test.y but it is giving undefined reference for the functions defined in libcustom.so .What is wrong with my makefile below. 我使用该库中的函数在我的程序test.y ,但它给了中定义的功能未定义参考libcustom.so 。什么是错的我下面的生成文件。

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 

It has been long time since last time I write a serious makefile , please point it out if I am wrong. 自上次编写严肃的makefile以来已经有很长时间了,如果我写错了,请指出。

there are ways to avoid encounter such issue by using implicit rules: 有一些方法可以通过使用隐式规则来避免遇到此类问题:

.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

then you avoided all painful stuff. 然后您避免了所有痛苦的事情。

in general, it's better to generate .o files explicitly then use linker to deal with them, such that if a build fails, you will definite know what's wrong with it, specifically compile time error, or linker error. 通常,最好显式地生成.o文件,然后使用链接器进行处理,这样,如果构建失败,则您将明确知道它出了什么问题,特别是编译时错误或链接器错误。

about the cause of your question, I think you should put -lcustom in a correct position to make it work. 关于问题的原因,我认为您应该将-lcustom放在正确的位置以使其起作用。 I rarely see people put -l flag right after gcc so I am pretty sure it's not correct. 我很少看到有人在gcc之后放-l标志,所以我很确定这是不正确的。 I would guess you should put it at the very end. 我想您应该把它放在最后。

PS: in my comment, nm is a tool to list out the symbols in a object file. PS:在我的评论中, nm是列出目标文件中符号的工具。 specifically, in your output, T means the function is in text segment and it's exported so it should be able to be linked. 具体来说,在您的输出中, T表示该函数位于文本段中并且已导出,因此应该可以链接。 check man nm for more info. 有关更多信息,请检查man nm

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM