Stringify macro with GNU gfortran

前端 未结 3 568
难免孤独
难免孤独 2020-12-19 09:20

How can I stringify a preprocessor macro with GNU gfortran? I would like to pass a macro definition to GNU gfortran which will then be used as a string in the code.

3条回答
  •  暖寄归人
    2020-12-19 10:03

    Although this is an old and answered question, I wanted to achieve macro stringification in gfortran without changing the default preprocessor or build process. I found that the preprocessor would do what I want, as long as there was no initial quotation mark on the line, therefore the desired stringification can be achieved by breaking lines with ampersands:

    astring = "&
    &MYMACRO"
    

    A caveat is that this really only works with the traditional preprocessor, and for examples breaks with intel ifort compiler, which is too smart to fall for this trick. My current solution is to define separate stringification macros for gfortran as:

    #ifdef __GFORTRAN__
    # define STRINGIFY_START(X) "&
    # define STRINGIFY_END(X) &X"
    #else /* default stringification */
    # define STRINGIFY_(X) #X
    # define STRINGIFY_START(X) &
    # define STRINGIFY_END(X) STRINGIFY_(X)
    #endif
    
    program test
    implicit none
    character (len=:), allocatable :: astring
    astring = STRINGIFY_START(MYMACRO)
    STRINGIFY_END(MYMACRO)
    write (*, *) astring
    end program test
    

    It looks really ugly, but it does get the job done.

提交回复
热议问题