Skip to content

Instantly share code, notes, and snippets.

@scivision
Last active December 6, 2023 03:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save scivision/ebe0f1030f0c8b8403b50a9b7d81a8cc to your computer and use it in GitHub Desktop.
Save scivision/ebe0f1030f0c8b8403b50a9b7d81a8cc to your computer and use it in GitHub Desktop.
CMake C++ library and Fortran main program LINKER_LANGUAGE heuristic issue

CMake LINKER_LANGUAGE heuristic: C++ lib and Fortran main

With Linux and Intel oneAPI or NVIDIA HPC SDK, regardless of CMake version or compiler version, this CMakeLists.txt will fail to build with error as below if the "LINKER_LANGUAGE" property is not set.

/lib/../lib64/crt1.o: in function `_start':
(.text+0x1b): undefined reference to `main'

This Discourse seemed to indicate that's just the way it is.

However, this issue may indicate there could be a CMake-internal fix.

cmake_minimum_required(VERSION 3.19)
project(link LANGUAGES CXX Fortran)
file(GENERATE OUTPUT lib.cpp CONTENT "extern \"C\" int addtwo(int N){ return N + 2; }")
file(GENERATE OUTPUT main.f90 CONTENT "program adder
use, intrinsic :: iso_c_binding, only : C_INT
implicit none
interface
integer(C_INT) function addtwo(N) bind(C)
import C_INT
integer(C_INT), intent(in), value :: N
end function
end interface
if (addtwo(2) /= 4) error stop 'failed to add 2+2 with C++ library'
end program
")
add_executable(main_f main.f90 lib.cpp)
# comment out this line, and CMake fails to build with Linux Intel oneAPI or NVHPC
set_property(TARGET main_f PROPERTY LINKER_LANGUAGE Fortran)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment