I have a C++ project that uses Fortran.
When compiling under GCC, I can link in Fortran statically using target_link_libraries(Project -static-libgfortran gfortran).
However, I am now compiling the same project using Clang, which means instead of gfortran I am using Flang. (flang-new version 15.0.7)
If I don't include any replacement, I get a lot of undefined symbols, like _FortranAioBeginExternalFormattedOutput.
If I try to swap out those two with just "flang", it fails, saying:
lld: error: unable to find library -lflang
LLVM has a single sentence on linking flang, which I don't follow:
"After the LLVM IR is created, the flang driver invokes LLVM’s existing infrastructure to generate object code and invoke a linker to create the executable file."
How do I link in Flang the same way I did GFortran?
-static-libgfortranis listed in https://clang.llvm.org/docs/ClangCommandLineReference.html#fortran-compilation-flags. Try usingtarget_compile_options(Project PUBLIC -static-libgfortran)(orPRIVATE).For Classic Flang
The compiler option docs don't list a
-static-libgfortranflag, but they do list a-static-flang-libs. Try using that instead. But since it's listed as a compiler option, I'd try usingtarget_compile_options.If you want to support both GFortran and Flang, then wrap the
target_link_options/target_link_librariescalls inif(CMAKE_CXX_COMPILER_ID STREQUAL "GNU")orif(CMAKE_CXX_COMPILER_ID STREQUAL "Flang")(see docs forCMAKE_LANG_COMPILER_ID), or use the$<Fortran_COMPILER_ID:...>generator expression.If this is a linker flag, I'd recommend
target_link_optionsfor linker options instead oftarget_link_librariesjust for readability's sake (usingtarget_link_librariesshould work too though according to the docs).Note: I found the info about the
-static-flag-libsflag by googling ""flang" "-static-libgfortran"", where my top search result was this SciVision post, which showed the-static-flang-libsflag. Then a google of ""flang" "-static-flang-libs"" led me to the Flang GitHub. Tip for googling flags that start with a dash: enclose in double-quotes to avoid it being used as a exclusion operator.