Cmake配置文件,用于从FORTRAN代码调用的C++函数中调用C++代码

Cmake configutarion file for calling a C++ code from a C++ function called by a FORTRAN code

本文关键字:C++ 代码 调用 函数 FORTRAN 配置文件 用于 Cmake      更新时间:2023-10-16

我一直在使用FORTRAN代码main.f90向func.cpp发送一个数组,该数组将调用C++代码addition.cpp&addition.h。该代码在centos4平台上运行正常,但当我将其移动到centos6平台时,它会给我带来错误。我曾尝试在两台机器上使用相同版本的gcc(4.3.0),或在centos6中使用更新的4.4.7版本,但问题没有解决。我将代码的简化版本附加为

main.f90:

 program main
   use iso_c_binding
   implicit none
   interface
      function func (a) bind (C, name="func")
         import
         integer(c_int):: func
         real(c_double), dimension(1:4), intent(in):: a
      end function func
   end interface
   real(c_double), dimension(1:4):: a = [ 2.3, 3.4, 4.5, 5.6 ]
   integer(c_int):: result
   result = func(a)
   write (*,*) result
end program main

func.cpp:

#include <iostream>
#include "addition.h"
using namespace std;
#ifdef __cplusplus
  extern"C" {
#endif
void *__gxx_personality_v0;
int func(double a[]) {
   int i;
   for(i=0; i<4; i++) {
       cout << a[i] << endl;
   }
   int z;
   z = addition (5,3);
   cout << z << endl;
   return 0;
}
#ifdef __cplusplus
  }
#endif

addition.cpp:

#include <iostream>
#include "addition.h"
using namespace std;
int addition (int a, int b)
{
 int r;
 r = a + b;
 return r;
}

附加.h:

#ifndef ADDITION_H
#define   ADDITION_H
int addition (int a, int b);
#endif /* ADDITION_H */

CMakeLists.txt:

PROJECT(test)
cmake_minimum_required(VERSION 2.6)
enable_language(C Fortran)
# Setting the compilers
set (CMAKE_Fortran_COMPILER /usr/bin/gfortran)
set (CMAKE_CXX_COMPILER /usr/bin/g++)
# Setting the flags
set (CMAKE_CXX_FLAGS "-lgfortran")
set_source_files_properties(main.f90 func.cpp PROPERTIES COMPILE_FLAGS -c)
# Making the executable
ADD_EXECUTABLE(test.exe main.f90 func.cpp addition.cpp addition.h)

我现在得到的错误是:

/usr/lib/gcc/x86_64-redhat-linux/4.4.7/../../../../lib64/crt1.o: In function `_start':
(.text+0x20): undefined reference to `main'
collect2: ld returned 1 exit status
make[2]: *** [test.exe] Error 1
make[1]: *** [CMakeFiles/test.exe.dir/all] Error 2
make: *** [all] Error 2

我感谢在解决这个问题上提供的任何帮助。

当主程序使用Fortran时,为什么要与g++链接?按另一种方式执行,链接到gfortran并添加-lstdc++

只需添加行:SET_TARGET_PROPERTIES(test.exe PROPERTIES LINKER_LANGUAGE Fortran)

或者使用更新的GCC。所有仍然受支持的GCC版本都可以使用您的原始设置。