FortranCInterface.cmake 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  1. # Distributed under the OSI-approved BSD 3-Clause License. See accompanying
  2. # file Copyright.txt or https://cmake.org/licensing for details.
  3. #[=======================================================================[.rst:
  4. FortranCInterface
  5. -----------------
  6. Fortran/C Interface Detection
  7. This module automatically detects the API by which C and Fortran
  8. languages interact.
  9. Module Variables
  10. ^^^^^^^^^^^^^^^^
  11. Variables that indicate if the mangling is found:
  12. ``FortranCInterface_GLOBAL_FOUND``
  13. Global subroutines and functions.
  14. ``FortranCInterface_MODULE_FOUND``
  15. Module subroutines and functions (declared by "MODULE PROCEDURE").
  16. This module also provides the following variables to specify
  17. the detected mangling, though a typical use case does not need
  18. to reference them and can use the `Module Functions`_ below.
  19. ``FortranCInterface_GLOBAL_PREFIX``
  20. Prefix for a global symbol without an underscore.
  21. ``FortranCInterface_GLOBAL_SUFFIX``
  22. Suffix for a global symbol without an underscore.
  23. ``FortranCInterface_GLOBAL_CASE``
  24. The case for a global symbol without an underscore,
  25. either ``UPPER`` or ``LOWER``.
  26. ``FortranCInterface_GLOBAL__PREFIX``
  27. Prefix for a global symbol with an underscore.
  28. ``FortranCInterface_GLOBAL__SUFFIX``
  29. Suffix for a global symbol with an underscore.
  30. ``FortranCInterface_GLOBAL__CASE``
  31. The case for a global symbol with an underscore,
  32. either ``UPPER`` or ``LOWER``.
  33. ``FortranCInterface_MODULE_PREFIX``
  34. Prefix for a module symbol without an underscore.
  35. ``FortranCInterface_MODULE_MIDDLE``
  36. Middle of a module symbol without an underscore that appears
  37. between the name of the module and the name of the symbol.
  38. ``FortranCInterface_MODULE_SUFFIX``
  39. Suffix for a module symbol without an underscore.
  40. ``FortranCInterface_MODULE_CASE``
  41. The case for a module symbol without an underscore,
  42. either ``UPPER`` or ``LOWER``.
  43. ``FortranCInterface_MODULE__PREFIX``
  44. Prefix for a module symbol with an underscore.
  45. ``FortranCInterface_MODULE__MIDDLE``
  46. Middle of a module symbol with an underscore that appears
  47. between the name of the module and the name of the symbol.
  48. ``FortranCInterface_MODULE__SUFFIX``
  49. Suffix for a module symbol with an underscore.
  50. ``FortranCInterface_MODULE__CASE``
  51. The case for a module symbol with an underscore,
  52. either ``UPPER`` or ``LOWER``.
  53. Module Functions
  54. ^^^^^^^^^^^^^^^^
  55. .. command:: FortranCInterface_HEADER
  56. The ``FortranCInterface_HEADER`` function is provided to generate a
  57. C header file containing macros to mangle symbol names::
  58. FortranCInterface_HEADER(<file>
  59. [MACRO_NAMESPACE <macro-ns>]
  60. [SYMBOL_NAMESPACE <ns>]
  61. [SYMBOLS [<module>:]<function> ...])
  62. It generates in ``<file>`` definitions of the following macros::
  63. #define FortranCInterface_GLOBAL (name,NAME) ...
  64. #define FortranCInterface_GLOBAL_(name,NAME) ...
  65. #define FortranCInterface_MODULE (mod,name, MOD,NAME) ...
  66. #define FortranCInterface_MODULE_(mod,name, MOD,NAME) ...
  67. These macros mangle four categories of Fortran symbols, respectively:
  68. * Global symbols without '_': ``call mysub()``
  69. * Global symbols with '_' : ``call my_sub()``
  70. * Module symbols without '_': ``use mymod; call mysub()``
  71. * Module symbols with '_' : ``use mymod; call my_sub()``
  72. If mangling for a category is not known, its macro is left undefined.
  73. All macros require raw names in both lower case and upper case.
  74. The options are:
  75. ``MACRO_NAMESPACE``
  76. Replace the default ``FortranCInterface_`` prefix with a given
  77. namespace ``<macro-ns>``.
  78. ``SYMBOLS``
  79. List symbols to mangle automatically with C preprocessor definitions::
  80. <function> ==> #define <ns><function> ...
  81. <module>:<function> ==> #define <ns><module>_<function> ...
  82. If the mangling for some symbol is not known then no preprocessor
  83. definition is created, and a warning is displayed.
  84. ``SYMBOL_NAMESPACE``
  85. Prefix all preprocessor definitions generated by the ``SYMBOLS``
  86. option with a given namespace ``<ns>``.
  87. .. command:: FortranCInterface_VERIFY
  88. The ``FortranCInterface_VERIFY`` function is provided to verify
  89. that the Fortran and C/C++ compilers work together::
  90. FortranCInterface_VERIFY([CXX] [QUIET])
  91. It tests whether a simple test executable using Fortran and C (and C++
  92. when the CXX option is given) compiles and links successfully. The
  93. result is stored in the cache entry ``FortranCInterface_VERIFIED_C``
  94. (or ``FortranCInterface_VERIFIED_CXX`` if ``CXX`` is given) as a boolean.
  95. If the check fails and ``QUIET`` is not given the function terminates with a
  96. fatal error message describing the problem. The purpose of this check
  97. is to stop a build early for incompatible compiler combinations. The
  98. test is built in the ``Release`` configuration.
  99. Example Usage
  100. ^^^^^^^^^^^^^
  101. .. code-block:: cmake
  102. include(FortranCInterface)
  103. FortranCInterface_HEADER(FC.h MACRO_NAMESPACE "FC_")
  104. This creates a "FC.h" header that defines mangling macros ``FC_GLOBAL()``,
  105. ``FC_GLOBAL_()``, ``FC_MODULE()``, and ``FC_MODULE_()``.
  106. .. code-block:: cmake
  107. include(FortranCInterface)
  108. FortranCInterface_HEADER(FCMangle.h
  109. MACRO_NAMESPACE "FC_"
  110. SYMBOL_NAMESPACE "FC_"
  111. SYMBOLS mysub mymod:my_sub)
  112. This creates a "FCMangle.h" header that defines the same ``FC_*()``
  113. mangling macros as the previous example plus preprocessor symbols
  114. ``FC_mysub`` and ``FC_mymod_my_sub``.
  115. Additional Manglings
  116. ^^^^^^^^^^^^^^^^^^^^
  117. FortranCInterface is aware of possible ``GLOBAL`` and ``MODULE`` manglings
  118. for many Fortran compilers, but it also provides an interface to specify
  119. new possible manglings. Set the variables::
  120. FortranCInterface_GLOBAL_SYMBOLS
  121. FortranCInterface_MODULE_SYMBOLS
  122. before including FortranCInterface to specify manglings of the symbols
  123. ``MySub``, ``My_Sub``, ``MyModule:MySub``, and ``My_Module:My_Sub``.
  124. For example, the code:
  125. .. code-block:: cmake
  126. set(FortranCInterface_GLOBAL_SYMBOLS mysub_ my_sub__ MYSUB_)
  127. # ^^^^^ ^^^^^^ ^^^^^
  128. set(FortranCInterface_MODULE_SYMBOLS
  129. __mymodule_MOD_mysub __my_module_MOD_my_sub)
  130. # ^^^^^^^^ ^^^^^ ^^^^^^^^^ ^^^^^^
  131. include(FortranCInterface)
  132. tells FortranCInterface to try given ``GLOBAL`` and ``MODULE`` manglings.
  133. (The carets point at raw symbol names for clarity in this example but
  134. are not needed.)
  135. #]=======================================================================]
  136. #-----------------------------------------------------------------------------
  137. # Execute at most once in a project.
  138. if(FortranCInterface_SOURCE_DIR)
  139. return()
  140. endif()
  141. cmake_policy(PUSH)
  142. cmake_policy(SET CMP0007 NEW)
  143. #-----------------------------------------------------------------------------
  144. # Verify that C and Fortran are available.
  145. foreach(lang C Fortran)
  146. if(NOT CMAKE_${lang}_COMPILER_LOADED)
  147. message(FATAL_ERROR
  148. "FortranCInterface requires the ${lang} language to be enabled.")
  149. endif()
  150. endforeach()
  151. #-----------------------------------------------------------------------------
  152. set(FortranCInterface_SOURCE_DIR ${CMAKE_ROOT}/Modules/FortranCInterface)
  153. # MinGW's make tool does not always like () in the path
  154. if("${CMAKE_GENERATOR}" MATCHES "MinGW" AND
  155. "${FortranCInterface_SOURCE_DIR}" MATCHES "[()]")
  156. file(COPY ${FortranCInterface_SOURCE_DIR}/
  157. DESTINATION ${CMAKE_BINARY_DIR}/CMakeFiles/FortranCInterfaceMinGW)
  158. set(FortranCInterface_SOURCE_DIR ${CMAKE_BINARY_DIR}/CMakeFiles/FortranCInterfaceMinGW)
  159. endif()
  160. # Create the interface detection project if it does not exist.
  161. if(NOT FortranCInterface_BINARY_DIR)
  162. set(FortranCInterface_BINARY_DIR ${CMAKE_BINARY_DIR}/CMakeFiles/FortranCInterface)
  163. include(${FortranCInterface_SOURCE_DIR}/Detect.cmake)
  164. endif()
  165. # Load the detection results.
  166. include(${FortranCInterface_BINARY_DIR}/Output.cmake)
  167. #-----------------------------------------------------------------------------
  168. function(FortranCInterface_HEADER file)
  169. # Parse arguments.
  170. if(IS_ABSOLUTE "${file}")
  171. set(FILE "${file}")
  172. else()
  173. set(FILE "${CMAKE_CURRENT_BINARY_DIR}/${file}")
  174. endif()
  175. set(MACRO_NAMESPACE "FortranCInterface_")
  176. set(SYMBOL_NAMESPACE)
  177. set(SYMBOLS)
  178. set(doing)
  179. foreach(arg ${ARGN})
  180. if("x${arg}" MATCHES "^x(SYMBOLS|SYMBOL_NAMESPACE|MACRO_NAMESPACE)$")
  181. set(doing "${arg}")
  182. elseif("x${doing}" MATCHES "^x(SYMBOLS)$")
  183. list(APPEND "${doing}" "${arg}")
  184. elseif("x${doing}" MATCHES "^x(SYMBOL_NAMESPACE|MACRO_NAMESPACE)$")
  185. set("${doing}" "${arg}")
  186. set(doing)
  187. else()
  188. message(AUTHOR_WARNING "Unknown argument: \"${arg}\"")
  189. endif()
  190. endforeach()
  191. # Generate macro definitions.
  192. set(HEADER_CONTENT)
  193. set(_desc_GLOBAL "/* Mangling for Fortran global symbols without underscores. */")
  194. set(_desc_GLOBAL_ "/* Mangling for Fortran global symbols with underscores. */")
  195. set(_desc_MODULE "/* Mangling for Fortran module symbols without underscores. */")
  196. set(_desc_MODULE_ "/* Mangling for Fortran module symbols with underscores. */")
  197. foreach(macro GLOBAL GLOBAL_ MODULE MODULE_)
  198. if(FortranCInterface_${macro}_MACRO)
  199. string(APPEND HEADER_CONTENT "
  200. ${_desc_${macro}}
  201. #define ${MACRO_NAMESPACE}${macro}${FortranCInterface_${macro}_MACRO}
  202. ")
  203. endif()
  204. endforeach()
  205. # Generate symbol mangling definitions.
  206. if(SYMBOLS)
  207. string(APPEND HEADER_CONTENT "
  208. /*--------------------------------------------------------------------------*/
  209. /* Mangle some symbols automatically. */
  210. ")
  211. endif()
  212. foreach(f ${SYMBOLS})
  213. if("${f}" MATCHES ":")
  214. # Module symbol name. Parse "<module>:<function>" syntax.
  215. string(REPLACE ":" ";" pieces "${f}")
  216. list(GET pieces 0 module)
  217. list(GET pieces 1 function)
  218. string(TOUPPER "${module}" m_upper)
  219. string(TOLOWER "${module}" m_lower)
  220. string(TOUPPER "${function}" f_upper)
  221. string(TOLOWER "${function}" f_lower)
  222. if("${function}" MATCHES "_")
  223. set(form "_")
  224. else()
  225. set(form "")
  226. endif()
  227. if(FortranCInterface_MODULE${form}_MACRO)
  228. string(APPEND HEADER_CONTENT "#define ${SYMBOL_NAMESPACE}${module}_${function} ${MACRO_NAMESPACE}MODULE${form}(${m_lower},${f_lower}, ${m_upper},${f_upper})\n")
  229. else()
  230. message(AUTHOR_WARNING "No FortranCInterface mangling known for ${f}")
  231. endif()
  232. else()
  233. # Global symbol name.
  234. if("${f}" MATCHES "_")
  235. set(form "_")
  236. else()
  237. set(form "")
  238. endif()
  239. string(TOUPPER "${f}" f_upper)
  240. string(TOLOWER "${f}" f_lower)
  241. if(FortranCInterface_GLOBAL${form}_MACRO)
  242. string(APPEND HEADER_CONTENT "#define ${SYMBOL_NAMESPACE}${f} ${MACRO_NAMESPACE}GLOBAL${form}(${f_lower}, ${f_upper})\n")
  243. else()
  244. message(AUTHOR_WARNING "No FortranCInterface mangling known for ${f}")
  245. endif()
  246. endif()
  247. endforeach()
  248. # Store the content.
  249. configure_file(${FortranCInterface_SOURCE_DIR}/Macro.h.in ${FILE} @ONLY)
  250. endfunction()
  251. function(FortranCInterface_VERIFY)
  252. # Check arguments.
  253. set(lang C)
  254. set(quiet 0)
  255. set(verify_cxx 0)
  256. foreach(arg ${ARGN})
  257. if("${arg}" STREQUAL "QUIET")
  258. set(quiet 1)
  259. elseif("${arg}" STREQUAL "CXX")
  260. set(lang CXX)
  261. set(verify_cxx 1)
  262. else()
  263. message(FATAL_ERROR
  264. "FortranCInterface_VERIFY - called with unknown argument:\n ${arg}")
  265. endif()
  266. endforeach()
  267. if(NOT CMAKE_${lang}_COMPILER_LOADED)
  268. message(FATAL_ERROR
  269. "FortranCInterface_VERIFY(${lang}) requires ${lang} to be enabled.")
  270. endif()
  271. # Build the verification project if not yet built.
  272. if(NOT DEFINED FortranCInterface_VERIFIED_${lang})
  273. set(_desc "Verifying Fortran/${lang} Compiler Compatibility")
  274. message(STATUS "${_desc}")
  275. # Build a sample project which reports symbols.
  276. set(CMAKE_TRY_COMPILE_CONFIGURATION Release)
  277. try_compile(FortranCInterface_VERIFY_${lang}_COMPILED
  278. ${FortranCInterface_BINARY_DIR}/Verify${lang}
  279. ${FortranCInterface_SOURCE_DIR}/Verify
  280. VerifyFortranC # project name
  281. VerifyFortranC # target name
  282. CMAKE_FLAGS -DVERIFY_CXX=${verify_cxx}
  283. -DCMAKE_VERBOSE_MAKEFILE=ON
  284. "-DCMAKE_C_FLAGS:STRING=${CMAKE_C_FLAGS}"
  285. "-DCMAKE_CXX_FLAGS:STRING=${CMAKE_CXX_FLAGS}"
  286. "-DCMAKE_Fortran_FLAGS:STRING=${CMAKE_Fortran_FLAGS}"
  287. "-DCMAKE_C_FLAGS_RELEASE:STRING=${CMAKE_C_FLAGS_RELEASE}"
  288. "-DCMAKE_CXX_FLAGS_RELEASE:STRING=${CMAKE_CXX_FLAGS_RELEASE}"
  289. "-DCMAKE_Fortran_FLAGS_RELEASE:STRING=${CMAKE_Fortran_FLAGS_RELEASE}"
  290. OUTPUT_VARIABLE _output)
  291. file(WRITE "${FortranCInterface_BINARY_DIR}/Verify${lang}/output.txt" "${_output}")
  292. # Report results.
  293. if(FortranCInterface_VERIFY_${lang}_COMPILED)
  294. message(STATUS "${_desc} - Success")
  295. file(APPEND ${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeOutput.log
  296. "${_desc} passed with the following output:\n${_output}\n\n")
  297. set(FortranCInterface_VERIFIED_${lang} 1 CACHE INTERNAL "Fortran/${lang} compatibility")
  298. else()
  299. message(STATUS "${_desc} - Failed")
  300. file(APPEND ${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeError.log
  301. "${_desc} failed with the following output:\n${_output}\n\n")
  302. set(FortranCInterface_VERIFIED_${lang} 0 CACHE INTERNAL "Fortran/${lang} compatibility")
  303. endif()
  304. unset(FortranCInterface_VERIFY_${lang}_COMPILED CACHE)
  305. endif()
  306. # Error if compilers are incompatible.
  307. if(NOT FortranCInterface_VERIFIED_${lang} AND NOT quiet)
  308. file(READ "${FortranCInterface_BINARY_DIR}/Verify${lang}/output.txt" _output)
  309. string(REPLACE "\n" "\n " _output "${_output}")
  310. message(FATAL_ERROR
  311. "The Fortran compiler:\n ${CMAKE_Fortran_COMPILER}\n"
  312. "and the ${lang} compiler:\n ${CMAKE_${lang}_COMPILER}\n"
  313. "failed to compile a simple test project using both languages. "
  314. "The output was:\n ${_output}")
  315. endif()
  316. endfunction()
  317. # Restore including context policies.
  318. cmake_policy(POP)