Jason Maldonis
Jason Maldonis

Reputation: 337

How to define a variable in a makefile and then use it within Fortran code

I am trying to define a variable in a makefile, and then depending on whether that variable is set, change which code block is compiled in my Fortran routine.

Simple example I can't get working:

program test
    implicit none
    integer :: a
#ifdef MYVAR
    a = 1
#else
    a = 0
#endif
    write(*,*) a
end program test

My makefile is:

MYVAR=1
all:
    ifort temp.F90 -fpp
    echo $(MYVAR)

The echo $(MYVAR) line correctly prints 1. However, when the test program is compiled it sets a=0. How do I get the Fortran code to recognize MYVAR?

Upvotes: 3

Views: 827

Answers (2)

Kyle Kanos
Kyle Kanos

Reputation: 3264

You need to add an extra flag

OPTIONS = -DMYVAR=$(MYVAR)

and then you compile it with

all:
    ifort $(OPTIONS) <file.f90> -fpp

And you should be good to go.

Upvotes: 1

Alexander Vogt
Alexander Vogt

Reputation: 18098

You need to specify the variable at compile time (in your Makefile) using -D:

all:
    ifort -DMYVAR=1 temp.F90 -fpp
    echo $(MYVAR)

Or, since you just check whether it is defined or not:

all:
    ifort -DMYVAR temp.F90 -fpp
    echo $(MYVAR)

Upvotes: 1

Related Questions