liv2hak
liv2hak

Reputation: 15010

Makefile linking against a library

I have the following makefile.I have the shared library lcustom in the path /usr/local/lib. 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.

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 

Upvotes: 0

Views: 95

Answers (1)

Jason Hu
Jason Hu

Reputation: 6333

It has been long time since last time I write a serious makefile, please point it out if I am wrong.

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.

about the cause of your question, I think you should put -lcustom in a correct position to make it work. I rarely see people put -l flag right after gcc so I am pretty sure it's not correct. 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. specifically, in your output, T means the function is in text segment and it's exported so it should be able to be linked. check man nm for more info.

Upvotes: 2

Related Questions