Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compile different c files with different CFLAGS using Makefile?

Tags:

makefile

People also ask

How do I run multiple files in makefile?

If you just want program1 , you can run just make (it will run the first target). If you just want program2 , run make program2 . You have more control. And of course, a target all: program1 program2 will do just that (being it the first, running your 2 other targets).

How do I add CFLAGS in makefile?

It should be CFLAGS := -Wall -Wextra $(CFLAGS) , the difference is that CFLAGS is explicitly appended. So for example, you may set -Og , but user don't want optimization and passes CFLAGS=-O0 on command line. By using CFLAGS += -Og your -Og will take over the user provided value.


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 $<

The approach taken by linux kernel build system:

CFLAGS += $(CFLAGS-$@)

And then,

CFLAGS-A.o += -DEXTRA
CFLAGS-B.o += -DEXTRA

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]