问题描述
用于连接的C预处理器宏( ##
)在使用gfortran的Mac上似乎不起作用。在其他系统上使用其他Fortran编译器可以工作,因此我正在寻找gfortran的解决方法。我必须使用 ##
来创建许多变量,所以我离不开它们。
示例代码:
#define CONCAT(x,y) x ## y
程序主体
整数,参数:: CONCAT(ID,2)= 3
print *,Hello,ID_2
结束程序main
MAC上的gfortran编译错误
gfortran m.F90 -om
m.F90:5.23:
integer,parameter :: ID ## 2 = 3
1
错误:PARAMETER at(1 )缺少初始化程序
##
在gfortran(任何操作系统,不仅仅是Mac)中都不起作用,因为它以传统模式运行CPP。
根据传统模式下正确的操作符是 x / ** / y
,所以您必须区分不同的编译器:
#ifdef __GFORTRAN__
#define CONCAT(x, y)x / ** / y
#else
#define CONCAT(x,y)x ## y
#endif
其他()使用这种形式,当宏传递给CONCAT时表现得更好(通过):
#ifdef __GFORTRAN__
pre>
#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 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.Example code:
#define CONCAT(x,y) x##y program main integer, parameter:: CONCAT(ID,2) = 3 print*,"Hello", ID_2 end program main
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
解决方案
##
doesn't work in gfortran (any OS, not just Mac) because it runs CPP in the traditional mode.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
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在宏中连接字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!