Search code examples
binaryfortranenvironmenthardcode

Fortran: Hardcode some code in dependency on an environment variable


Hey there, if the env var "XYZ" is set WHILE compiling, than I want the part:

write (STDOUT,*) "Compiled with XYZ"
here one more function call bla()

to be compiled into the binary. If not, than not. Any way to do it? Thanks a lot!


Solution

  • You can't check environment variables while compiling, but you can pass options to the compiler -- termed preprocessing. This isn't heavily documented, but works with at least gfortran and intel ifort. On the compile line use, or not, "-DMYOPTION" (or whatever option name you select). Then in the code:

    #ifdef MYOPTION
    Fortran source code
    #else
    Fortran source code
    #endif
    

    Apparently that the preprocessor lines must start in the first column.

    If you use filetype "F90" the preprocessor will be automatically invoked, otherwise you can use a compiler option to invoke this step.

    Maybe this will answer your need? If not, you could you a command script to check the environment variable and use different compile commands depending on its value, to make the preprocessor method respond to an environment variable.

    Of course, you can check environment variables at run-time with the intrinsic get_environment_variable .. simply using if statements to respond to a value might be easier.