tags:

views:

358

answers:

2

Hi, all. Let's say I have a program that contains a long list of C source files, A.c, B.c, ...., Z.c, now I want to compile A.c, B.c with certain CFLAGS, and compile the rest part of source files with a different CFLAGS value.

How to write a Makefile to do the above described job? currently what I am doing in my Makefile is:

OBJ=[all other .o files here, e.g. D.o, D.o, E.o .... Z.o]
SPECIAL_OBJS=A.o B.o

all: $(OBJ) $(SPECIAL_OBJS)

$(SPECIAL_OBJS): 
     @echo [Compiling]: $(@:.o=.c)
     $(CC) [SOME OTHER GCC OPTIONS HERE] $(CFLAGS) -c $(@:.o=.c) -o $@

%.o: %.c
     @echo [Compiling]: $<
     $(CC) $(CFLAGS) -o $@ -c $<

It works, but looks just stupid/complicated. Can anyone help to point out what is the recommended way of doing this in Makefile? thanks!

A: 

I can't answer the question for raw makefiles, but if you are willing to use automake it is trivial:

foo_CFLAGS = [options passed to CC only when building foo]
William Pursell
When using automake like this, can "foo" be any kind of target (e.g. object file), or does it have to be a final target (executable or library)?
Dan Moulding
Using primaries like this applies to final targets and all intermediate targets. To apply only to intermediate targets (eg .o files), you can write explicit rules into the Makefile.am
William Pursell
+8  A: 

Try using target-specific variables. A target-specific variable is declared like this:

TARGET: VAR := foo  # Any valid form of assignment may be used ( =, :=, +=, ?=)

Now when the target named TARGET is being made, the variable named VAR will have the value "foo".

Using target-specific variables, you could do this, for example:

OBJ=[all other .o files here, e.g. D.o, D.o, E.o .... Z.o]
SPECIAL_OBJS=A.o B.o

all: $(OBJ) $(SPECIAL_OBJS)

$(SPECIAL_OBJS): EXTRA_FLAGS := -std=c99   # Whatever extra flags you need

%.o: %.c
     @echo [Compiling]: $<
     $(CC) $(CFLAGS) $(EXTRA_FLAGS) -o $@ -c $<
Dan Moulding