开发者

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()
开发者_StackOverflow社区

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


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.


As part of the Fortran 2008 standard, there are intrinsic functions for finding the compiler options and version it was compiled with. compiler options and compiler version. Fortran compilers are slowly coming up to date with the new standard; gfortran has it, it doesn't look like ifort 12 does yet:

program compilerinfo
    use iso_fortran_env
    implicit none

    print *,'This program was compiled with ', compiler_version()
    print *,'with flags ', compiler_options()
end program compilerinfo

and running gives

$ ./compilerinfo
 This program was compiled with GCC version 4.6.0
 with flags -mtune=generic -march=x86-64


NoOnly very newest Fortran compilers provide such a feature.

The nearest mechanism would be to write a program which obtains the environment variable and writes a Fortran subroutine containing the information needed. Add to the project build:

  1. Running the program to grab the environment variable and write the subroutine
  2. Compile the subroutine
  3. Link the object into the rest of the project.

Edited to reflect Fortran 2008+ compilers

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜