Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
551 views
in Technique[技术] by (71.8m points)

macos - Concatenate strings in a macro using 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.

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

## 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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...