在Fortran程序中,检查是否使用" -g"

时间:2017-11-30 02:30:07

标签: debugging fortran gfortran

如果程序编译了调试标志-g,我希望添加一些额外的信息记录。我使用gfortran(虽然我认为if (compiledwithg()) then print *, extraNiceInfo endif 无处不在)。在这种情况下,单步执行程序在gdb中尤其繁琐。特别是,我希望有类似的东西:

#ifdef DEBUG

我知道在C程序中,人们通常会使用像{{1}}这样的东西,然后打印一些额外的信息。据我所知,Fortran中没有类似的功能。有谁知道这样的事情?

1 个答案:

答案 0 :(得分:5)

回答问题:是的,现在可以在现代版本的Fortran中知道哪些选项用于编译。由francescalus链接,COMPILER_OPTIONS()子程序是可行的方法。

  use iso_fortran_env

  logical :: compiled_with_g
  character(:), allocatable :: options

  options = compiler_options()

  compiled_with_g =  index(options, "-g") > 0

  print *, compiled_with_g
end

> gfortran-7 compiled_with_g.f90
> ./a.out 
 F
> gfortran-7 -g compiled_with_g.f90
> ./a.out 
 T

注意,它将在以-g开头或只包含子串-g的任何编译器选项上触发为true。我尝试使用" -g ",但是当字符串以此选项开头或结尾时,它会出现问题。您也可以将这两种特殊情况添加到if条件中。

您可以在任何地方使用#ifdef DEBUG并使用-cpp-fpp编译所有来源(取决于编译器)。

或者您可以在模块中定义全局常量

#ifdef DEBUG
  logical, parameter :: compiled_with_g  = .true.
#else
  logical, parameter :: compiled_with_g  = .false.
#endif

使用-cpp-fpp编译此模块。

您可以对函数compiledwithg()执行相同的操作,并仅在函数中使用宏。

或者您可以拥有这个非常小的模块的两个版本:

module debug_mod
  logical, parameter :: debug = .true.
end module

module debug_mod
  logical, parameter :: debug = .false.
end module

并设置您的构建系统(如Makefile)以使用正确的构建系统。如果参数为false,编译器将删除死代码,因此它与宏一样有效。

相关问题