Home > Software engineering >  How to pass ifdef keyword by using makefile?
How to pass ifdef keyword by using makefile?

Time:08-31

I want to use "#ifdef MYFLAG" in my C code to exclude certain code parts when the keyword "MYFLAG" is passed to the compiler. So far so good. The project is compiled with a makefile.

Now, I can't figure out yet if it is correct to write

$ ./project/ make -MYFLAG

and then set the #ifdef as true. It compiles the files, but the size of the output remains unchanged. Do changes have to be made in the Makefile to accept the keyword or is it enough to have #ifdef in the c code and pass it as above?

CodePudding user response:

What you need to do in your Makefile is check whether MYFLAG is set, then pass it to the compiler (typically with -D or /D). Example Makefile for this:

ifneq ("$(MYFLAG)", "")
        CFLAGS=-DMYFLAG=$(MYFLAG)
endif

.c.o:
        gcc -c $(CFLAGS) $<

The first three lines set CFLAGS depending on whether MYFLAG is set or not. Then in the rule how to compile .c files (last two lines), CFLAGS (which could be empty or contain -DMYFLAG is passed to the compile command (gcc -c).

Now just run make like

MYFLAG=1 make

and MYFLAG will be defined as 1.

CodePudding user response:

@treus's answer is good, but it has a sharp stick -- if you do two subsequent makes, one with MYFLAG set, and one without, any artifacts created by the first will be considered up to date, and not be rebuilt, even though the CFLAGS has changed. One solution to get around this:

Add a flag to the make line as so:

make MYFLAG=y

Then, in the makefile, process this first, as so:

ifdef MYFLAG
CFLAGS  = -DMYFLAG=$(MYFLAG)
endif

OBJ_SUFFIX := $(shell echo $(CFLAGS) | md5sum | head -c 6)

# not allowed changing CFLAGS below this line...

OBJDIR = objs/$(OBJ_SUFFIX)

$(OBJDIR):
    mkdir -p $(OBJDIR)

$(OBJDIR)/%.o: %.c | $(OBJDIR)
    $(CC) $(CFLAGS) -c -o $@ $<

...


This way, each time you change the CFLAGS, it will build to a different object directory, so artifacts will not be considered up to date incorrectly.

  • Related