Reputation: 135
I have a library that must be linked to 2 main codes, one in fortran and on in cxx.
I have this library in src/lib/CMakeLists.txt
:
ADD_LIBRARY(mylib a.f90 b.c c.cc)
and in src/main/CMakeLists.txt
, I have:
ADD_EXECUTABLE(mymain1 mymain1.f90)
TARGET_LINK_LIBRARIES(mymain1 mylib)
ADD_EXECUTABLE(mymain2 mymain2.cc)
TARGET_LINK_LIBRARIES(mymain2 mylib)
When compiling mymain1
, it use the CXX compiler to link instead of the Fortran one.
How can I tell cmake to use Fortran to link mymain1
and CXX to link mymain2
?
Upvotes: 0
Views: 64
Reputation: 65928
You may directly affect on language used for linking with LINKER_LANGUAGE property:
# Use Fortran compiler for link 'mymain1' executable
set_target_properties(mymain1 PROPERTIES LINKER_LANGUAGE Fortran)
Another way could be "teach" CMake to properly choose linker.
Without the library CMake would correctly select Fortran linker for mymain1
as it compiled only from Fortran sources, and C++ linker for mymain2
as it compiled only from C++ sources.
But linking with the library messes CMake: because the library mylib
is compiled from sources on several languages, CMake selects linker for it using some "preference scores" for languages (see CMAKE_<LANG>_LINKER_PREFERENCE variable). More likely, C++ "beats" Fortran in your case.
Moreover, when select linker language for mymain1
, CMake take into account language for the static library mylib
. Because of that C++ wins even for the executable built from Fortran sources only.
You may disable propagating library's language to the executable using variables CMAKE_<LANG>_LINKER_PREFERENCE_PROPAGATES:
# <place this *before* adding executables>
# Do not propagate language of C++ libraries to the executables.
set(CMAKE_CXX_LINKER_PREFERENCE_PROPAGATES OFF)
Upvotes: 2