0

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 
liv2hak
  • 14,472
  • 53
  • 157
  • 270

1 Answers1

2

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.

Jason Hu
  • 6,239
  • 1
  • 20
  • 41
  • you assessment about putting the `-l` option at the end does work.thanks. – liv2hak Aug 07 '15 at 00:17
  • I agree that your way of organizing the makefile is more readable. – liv2hak Aug 07 '15 at 00:18
  • I don't see gcc option there? – liv2hak Aug 07 '15 at 00:19
  • 1
    @liv2hak that's good. i haven't written c program for quite a while and i found i lost a lot of memory about it so i wasn't so sure. – Jason Hu Aug 07 '15 at 00:19
  • @liv2hak gcc option can be passed by `CFLAGS`. the makefile i showed uses `implicit rules`, which let `make` generate the rules automatically for you. in this case, it auto-generates rules for `gcc` and `ld`, so you don't code them out yourself. – Jason Hu Aug 07 '15 at 00:20