Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add additional source files in Makefile

Tags:

c

makefile

I have a Makefile that I use to build executable on mac os x, using mpicc compiler, linking mkl_lapack.h library. Now this Makefile is perfectly working, the only problem is that I don't know what to add if I want to compile Eigenvalues.c linking other .c files, if I want to link myfile.c where do I have to write it in Makefile?

MKL_INCLUDE=/opt/intel/mkl/include
MKLROOT=/opt/intel/mkl/lib

CC = mpicc
LD = mpicc
IFLAGS = -I$(MKL_INCLUDE)
CFLAGS = -Wall -O2 $(IFLAGS) -std=c99

LFLAGS =  $(MKLROOT)/libmkl_intel_lp64.a $(MKLROOT)/libmkl_sequential.a    $(MKLROOT)/libmkl_core.a  -lpthread -lm 

PROGRAMS = Eigenvalues

all: $(PROGRAMS)

Eigenvalues: 
    $(CC) $(CFLAGS) -o $@ $^ $(LFLAGS) 

%.o: %.c
    @echo C compiling $@
    $(CC) -c $(CFLAGS) -o $@ $<

clean:
    rm -rf *.o $(PROGRAMS)

Eigenvalues: Eigenvalues.c
like image 958
Ramy Al Zuhouri Avatar asked Feb 04 '26 08:02

Ramy Al Zuhouri


2 Answers

Simply have the Eigenvalues target depend on all the .o files (not the .c files, as you have!) that make up the application. Conventionally, the list of these objects is put in a variable:

PROGRAMS = Eigenvalues
Eigenvalues_OBJS = Eigenvalues.o foo.o bar.o #etc

all: $(PROGRAMS)

Eigenvalues: $(Eigenvalues_OBJS)
        $(CC) $(CFLAGS) -o $@ $^ $(LFLAGS) 

# delete the "Eigenvalues: Eigenvalues.c" line,
# leave everything else as you have it

By the way, since you are using the standard variable names $(CC) and $(CFLAGS), you can leave out the %.o: %.c rule entirely; Make has a built-in rule that does the same thing.

like image 113
zwol Avatar answered Feb 05 '26 22:02

zwol


Try this mate!

PROGRAMS = Eigenvalues

MKL_INCLUDE=/opt/intel/mkl/include 
MKLROOT=/opt/intel/mkl/lib 

IFLAGS = -I$(MKL_INCLUDE) 
CFLAGS = -Wall -O2 $(IFLAGS) -std=c99 

LFLAGS =  $(MKLROOT)/libmkl_intel_lp64.a $(MKLROOT)/libmkl_sequential.a
$(MKLROOT)/libmkl_core.a  -lpthread -lm  


all: $(PROGRAMS).c

OBJS = \
Eigenvalues.o \
myfile.o\

##############################################################################
.SUFFIXES : .c .o

CC = mpicc 
LD = mpicc 
RM = rm -rf

$(PROGRAMS).c : $(OBJS)
    $(CC) $(CFLAGS) -o $@ $^ $(LFLAGS)  

clean: 
    $(RM) *.o $(OBJS) $(PROGRAMS) 

.c.o :
    $(CC) -c $(CFLAGS) -o $@ $<
like image 22
Christian Avatar answered Feb 05 '26 22:02

Christian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!