flashdisk
flashdisk

Reputation: 3820

How to create makefile for lexical analyzer?

I want to make a make file for my lexical analyzer using flex ,I have tried to many templates of make files but it did not work so please help me build one here is the lines to compile the code:

lex -t lexical.l > lexical.c
cc -c -o lexical.o lexical.c
cc -o lexy lexical.o -ll

Upvotes: 0

Views: 459

Answers (3)

Olaf Dietsche
Olaf Dietsche

Reputation: 74088

GNU make has already defined the necessary rules for this. Just put this in a file named Makefile

LDLIBS = -ll

lexy: lexical.o

lexical.o: lexical.l

and run

$ make

and you're done.

Upvotes: 1

Jan
Jan

Reputation: 11726

If you're using GNU make you don't need a makefile at all. Built-in rules cover your use case.

Let's print built-in rules and see whether make knows how to transform '%.l' to '%.c'.

$ make -p | grep -A6 '\.l\.c'
make: *** No targets specified and no makefile found.  Stop.
.l.c:
#  Implicit rule search has not been done.
#  Modification time never checked.
#  File has not been updated.
#  recipe to execute (built-in):
    @$(RM) $@ 
     $(LEX.l) $< > $@

It does. In a similar way you can check that GNU make knows how to build '%.o' from '%.c' and a '%' executable from '%.o'.

Assuming that there's a lexical.l in the current directory and there's no makefile let's see how would make build lexical.

$ make -n lexical
rm -f lexical.c 
lex  -t lexical.l > lexical.c
cc    -c -o lexical.o lexical.c
cc   lexical.o   -o lexical
rm lexical.c lexical.o

Great. All we miss is the -ll flag for linking you asked for. Let's add it to LDLIBS.

$ make -n lexical LDLIBS=-ll
rm -f lexical.c 
lex  -t lexical.l > lexical.c
cc    -c -o lexical.o lexical.c
cc   lexical.o  -ll -o lexical
rm lexical.c lexical.o

Voilà! As a result your makefile can be as short as

LDLIBS=-ll
all: lexical

Upvotes: 7

Simon Richter
Simon Richter

Reputation: 29618

A starting point would be

LEX = lex

.l.c:
        $(LEX) -t $< >$@

.c.o:
        $(CC) -o $@ -c $<

lexy: lexical.o
        $(CC) -o $@ $^ -ll

This needs to be extended with clean rules, dependency tracking and so on, but I think you should be able to get the idea how Makefiles work.

Upvotes: 2

Related Questions