3

I would like to compile a C code multiple times through a Makefile by passing different parameters to the #define variable. Where should I put my noobie hands on?

In my C code I have a size definition for a matrix' dimensions through

#define N 500

I would like to compile it multiple times in a loop, but I can't get my head around on how to pass the

-DN=(different sizes) 

inside the Makefile.

The job would be structured as following: 1. make clean 2. make with -DN=certain size 3. run performance test and acquire results 4. repeat with different size.

My Makefile now looks like this:

exe_name = exe
CC = gcc
CFLAGS =  -g -O2 -ggdb
LDFLAGS = -lm -L. -Wall -Wextra
OMPFLAGS = -fopenmp

OBJS = ompmatmul.o

default: $(exe_name)

$(exe_name): $(OBJS) 
    $(CC) -o $@ $^ $(LDFLAGS) $(OMPFLAGS)

%.o: %.c
    $(CC) -c $< -o $@ $(CFLAGS) $(OMPFLAGS) 

clean: 
    rm -f $(OBJS) $(exe_name) *~

.PHONY: clean #Don't look for a file named 'clean' 

While the loop I would insert the make into is the following:

for size in $(seq 500 500 3000); do

    make clean
    make #define_new_size
        #do_performance_and_acquire_results
done
cyberZamp
  • 149
  • 1
  • 9
  • Perhaps I wasn't clear, sorry for that: I would like to know whether I can change (and especially how) the size of #define N through the use of a Makefile for N=500,1000,1500,..,3000 in a single run of my bash job, so to avoid tuning the parameter and recompile for each N. – cyberZamp Jan 08 '19 at 15:39
  • 3
    so `make size=$size` then the gcc command takes `-DN=$(size)` – Jean-François Fabre Jan 08 '19 at 15:39

2 Answers2

6

To pass a parameter to the make file, add the parameter like this:

make N=500

Then your makefile would contain:

ifndef N
    # provide a default
    N=500
endif

...

$(exe_name): $(OBJS) 
    $(CC) -DN=$(N) -o $@ $^ $(LDFLAGS) $(OMPFLAGS)    
dbush
  • 205,898
  • 23
  • 218
  • 273
1

To automate the tests, based on the excellent solution proposed by dbush, you could add the following to your Makefile:

SEQS := $(shell seq 500 500 3000)
TSTS := $(addprefix test-,$(SEQS))

.PHONY: tests $(TSTS)

tests: $(TSTS)

test-%:
    $(MAKE) clean
    $(MAKE) $(exe_name) N=$*
    $(MAKE) performance-test
Renaud Pacalet
  • 25,260
  • 3
  • 34
  • 51