2016-09-24 60 views
1

用于并置的C预处理器宏(##)在使用gfortran的Mac上似乎不起作用。在其他系统上使用其他Fortran编译器可以工作,因此我正在寻找gfortran的解决方法。我必须使用##来创建许多变量,所以我离不开它们。使用gfortran在宏中连接字符串

实施例的代码:对MAC

gfortran m.F90 -o m 
m.F90:5.23: 
integer, parameter:: ID##2 = 3 
         1 
Error: PARAMETER at (1) is missing an initializer 
+0

通常的策略是首先将文件传递给预处理器,然后编译预处理文件:http://stackoverflow.com/questions/38953392/can-cpp-preprocessing-statement-in-fortran-be-indented/ 38953582#38953582 – ewcz

+0

gfortran设置了tradcpp(gcc -E -traditional)以避免c99 //注释和Fortran并置之间的冲突。如上所述,典型的选择是明确使用不同的预处理器,例如通过Makefile。 – tim18

回答

2

##与gfortran

#define CONCAT(x,y) x##y 
program main 
    integer, parameter:: CONCAT(ID,2) = 3 
    print*,"Hello", ID_2 
end program main 

编译错误,因为它运行CPP在传统不gfortran工作(任何OS,不只是苹果机)模式

根据this thread the gfortran mailing list在传统模式中,正确的操作是x/**/y,所以你必须在不同的编译器之间的区别:

#ifdef __GFORTRAN__ 
#define CONCAT(x,y) x/**/y 
#else 
#define CONCAT(x,y) x ## y 
#endif 

其他(http://c-faq.com/cpp/oldpaste.html)使用这种形式,当宏传递到CONCAT其行为更好(通过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 

间接配方有助于扩大通过宏字符串连之前(这是太后晚期)。

+0

非常有用,非常感谢! – danny