[CMake] Fortran program linked with C++ library

Brad King brad.king at kitware.com
Tue Sep 3 10:46:05 EDT 2013


On 08/31/2013 10:50 AM, Marcin Wojdyr wrote:
> What's the best practice for linking Fortran program with C++ library?
> The library is external, built using autotools, either dynamic or static.
> 
> The problem is that runtime c++ library is not linked when the library
> is static.
> I though that the recommended way to deal with it is:
> 
> set_property(TARGET ${prog} PROPERTY LINKER_LANGUAGE CXX)

This tells CMake that your "main" is provided by C++, but IIUC
it is still Fortran.  You should still be able to link with the
Fortran front-end but need to get the C++ runtime library too.

One way to do this is to tell CMake that the library uses C++
using the IMPORTED_LINK_INTERFACE_LANGUAGES property on an
imported target:

 http://www.cmake.org/cmake/help/v2.8.11/cmake.html#prop_tgt:IMPORTED_LINK_INTERFACE_LANGUAGES

For example:

 add_library(externalCxxLib STATIC IMPORTED)
 set_target_properties(externalCxxLib PROPERTIES
   IMPORTED_LOCATION "/path/to/libexternalCxxLib.a"
   IMPORTED_LINK_INTERFACE_LANGUAGES "CXX"
   )
 target_link_libraries(myFortranExe externalCxxLib)

This should work if:

- The project enables both Fortan and CXX languages
- The C++ compiler used is the same as that used to
  build the static library

Then CMake has enough information to add the C++ runtime
library to the link line when linking to the static library.

-Brad


More information about the CMake mailing list