2016-09-24 63 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