Home > Mobile >  Using makefile with multiple C programs
Using makefile with multiple C programs

Time:04-16

I've written multiple C programs in different files and I want to run all three of them in the same time, on the same argv:

That's what I tried so far but its only running the last program digcmp.c:

CC=gcc
a_OBJS=lexcmp.o
b_OBJS=lencmp.o
c_OBJS=digcmp.o
EXEC=lex len dig
DEBUG = -g
CFLAGS = -std=c99  -Wall -Werror $(DEBUG)  #if you have CFLAGS you do not have to write for each file $(CC) -c $*.c!!!

lex: $(b_OBJS)
    $(CC) $(a_OBJS) -o $@


len: $(b_OBJS)
    $(CC) $(b_OBJS) -o $@


dig: $(c_OBJS)
    $(CC) $(c_OBJS) -o $@


lexcmp.o: lexcmp.c
lencmp.o: lencmp.c
digcmp.o: digcmp.c


clean: 
    rm -f lex $(a_OBJS)
    rm -f len $(b_OBJS)
    rm -f dig $(c_OBJS)

CodePudding user response:

The make program have many implicit rules. In fact they are what makes your lexcmp.o: lexcmp.c (etc.) rules work.

All you need is to list the rules to make the executable programs themselves:

lexcmp: lexcmp.o
lencmp: lencmp.o
digcmp: digcmp.o

The above is a perfectly fine Makefile on its own, and if you run e.g.

$ make lencmp

then the lencmp.c source file will be built into the object file lencmp.o which will then be linked into the executable lencmp program.

If you want specific compilation flags when building just set the CFLAGS variable and it will be used automatically. I also recommend a default target which might list all executable targets as dependencies to build all of them:

CFLAGS = -Wall -Wextra

.PHONY: all
all: lexcmp lencmp digcmp

This should really be enough to build all your executable files (skipping the object-file intermediate stage) with the flags you want.

The .PHONY target tells make that it's not supposed to generate a file with the name all.

  • Related