【问题标题】:Fortran and cpp option : How to protect a comma?Fortran 和 cpp 选项:如何保护逗号?
【发布时间】:2022-08-21 03:04:20
【问题描述】:

定义了一个选项(值 = 1 或 2)以在两条指令之间进行选择,我想与带有逗号的指令一起使用。

#define option 1

#if option == 1
#define my_instr(instr1, instr2) instr1
#else if option == 2
#define my_instr(instr1, instr2) instr2
#endif

它有效,但是当指令中有逗号时,我遇到了问题。

例如 :

program main

 my_instr(print *,"opt 1", print * ,"opt 2")

end program main

无法编译(gftran -cpp):args 太多。我很好。

因此,为了转义逗号,添加了括号:my_instr((print *,"opt 1"), (print * ,"opt 2"))

但由于括号,它不再编译。

我该如何解决?

【问题讨论】:

  • I found a solution. 将其发布为解决方案并接受答案。是的,要保留逗号,您必须将其放在括号内。
  • it is not recommanded to use VA_ARGS 不不,__VA_ARGS__ 是标准配置。使用空参数列表(...) 在技术上是不标准的。你必须(something, ...)。也就是说,我认为所有编译器都会编译得很好。
  • @KamilCuk。感谢cmets。我在__VA_ARGS__ 上发布了答案并修改了我的评论。不要犹豫,编辑它。会比我的回答好。

标签: fortran c-preprocessor preprocessor


【解决方案1】:

使用答案(https://stackoverflow.com/a/46311121/7462275),我找到了一个“解决方案”。

#define option 2

#define unparen(...) __VA_ARGS__

#if option == 1
#define my_instr(instr1, instr2) unparen instr1
#elif option == 2
#define my_instr(instr1, instr2) unparen instr2
#endif

 program main
 
   my_instr((print *,"opt 1"), (print * ,"opt 2"))

 end program main

但,

  1. gfortran -cpp 无法编译(__VA_ARGS__ 的问题)。所以,cpp -Pgfortran 之前使用
  2. __VA_ARGS__ :在没有 something 之前使用 __VA_ARGS__ 是不标准的(cf cmets of :
    Matthew D. Scholefield 在使用的​​答案中:需要注意的是,由于使用了可变参数宏,这仍然不符合 C 标准。
    和 KamilCuk 在这个问题)
  3. 即使没有逗号的指令也需要用括号括起来

【讨论】:

  • 你不需要unpareninvoke,只需要#define my_instr(instr1, instr2) really_unparen instr1
【解决方案2】:

这将选择正确的字符串。

#ifdef my_instr
#undef my_instr
#endif
#define my_instr(x) print *, x

#if option == 1
#define str "Opt 1"
#else if option == 2
#define str "Opt 2"
#endif

program foo
  my_instr(str)
end program foo

% gfortran -E -Doption=2 a.F90 | cat -s
# 1 "a.F90"
# 1 "<built-in>"
# 1 "<command-line>"
# 1 "a.F90"

program foo
  print *, "Opt 2"
end program foo

【讨论】:

  • 我同意你的看法。但print 只是一个例子。我正在寻找一个更通用的宏。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-09-20
  • 1970-01-01
  • 1970-01-01
  • 2015-07-20
  • 2023-02-11
  • 1970-01-01
  • 2018-03-12
相关资源
最近更新 更多