Search code examples
variablesmakefilefortranconditional-compilation

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?


Solution

  • 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.