使用 gfortran 在宏中连接字符串 [英] Concatenate strings in a macro using gfortran
问题描述
用于连接的 C 预处理器宏 (##
) 似乎不适用于使用 gfortran 的 Mac.在其他系统上使用其他 Fortran 编译器可以工作,所以我正在寻找 gfortran 的解决方法.我必须使用 ##
来创建许多变量,所以我不能没有它们.
The C preprocessor macro for concatenation (##
) does not seem to work on a Mac using gfortran. Using other Fortran compilers on other systems works so I am looking for a workaround for gfortran. I have to use the ##
to create many variables so I can't do without them.
示例代码:
#define CONCAT(x,y) x##y
program main
integer, parameter:: CONCAT(ID,2) = 3
print*,"Hello", ID_2
end program main
gfortran 在 MAC 上的编译错误
Compilation error with gfortran on MAC
gfortran m.F90 -o m
m.F90:5.23:
integer, parameter:: ID##2 = 3
1
Error: PARAMETER at (1) is missing an initializer
推荐答案
##
在 gfortran(任何操作系统,不只是 Mac)中不起作用,因为它在 traditional模式.
##
doesn't work in gfortran (any OS, not just Mac) because it runs CPP in the traditional mode.
根据 此线程 gfortran 邮件列表传统模式下正确的操作符是x/**/y
,所以必须区分不同的编译器:
According to this thread the gfortran mailing list the correct operator in the traditional mode is x/**/y
, so you must distinguish between different compilers:
#ifdef __GFORTRAN__
#define CONCAT(x,y) x/**/y
#else
#define CONCAT(x,y) x ## y
#endif
其他(http://c-faq.com/cpp/oldpaste.html) 使用这种形式,它在将宏传递给 CONCAT 时表现更好(通过 使用 Fortran 预处理器连接扩展宏和单词):
Others (http://c-faq.com/cpp/oldpaste.html) use this form, which behaves better when a macro passed to the CONCAT (via Concatenating an expanded macro and a word using the Fortran preprocessor):
#ifdef __GFORTRAN__
#define PASTE(a) a
#define CONCAT(a,b) PASTE(a)b
#else
#define PASTE(a) a ## b
#define CONCAT(a,b) PASTE(a,b)
#endif
间接公式有助于在连接字符串之前扩展传递的宏(之后为时已晚).
The indirect formulation helps to expand the passed macro before the strings are concatenated (it is too late after).
这篇关于使用 gfortran 在宏中连接字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!