2014-10-03 39 views
0

我一直在使用FORTRAN代碼main.f90將數組發送到func.cpp,它將調用C++代碼addition.cpp & addition.h。代碼在CentOS 4平臺上正常工作,但是當我將它移動到CentOS 6時,它給了我錯誤。我曾嘗試在兩臺機器上使用相同版本的gcc(4.3.0),或在CentOS 6中使用較新版本4.4.7,但問題未解決。我附上的代碼過於簡單化版本Cmake配置文件,用於從FORTRAN代碼調用的C++函數中調用C++代碼

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 

我欣賞解決這個問題的任何幫助。

+0

從我看到的輸出中我可以說問題出在fortran「main」文件中。顯然Fortran代碼不會生成「主」入口點。嘗試編譯一個簡單的Fortran代碼,不帶任何外部C++庫,看看它是否可行 – user3159253 2014-10-03 18:54:14

+0

另外,我會運行'make'(在CMake生成的Makefile(s))作爲'make VERBOSE = 1'來查看確切的命令由make(gcc,ld等)發佈,並且能夠一步一步地自行重現問題,而不需要任何「構建系統」,只有你自己,代碼,編譯器和鏈接器。 – user3159253 2014-10-03 18:57:32

+0

當我運行沒有任何cpp文件的簡單Fortran代碼時,它可以正常工作。我刪除了與addition.cpp和addition.h相關的所有內容,以使它更簡單(所以只需要調用func.cpp左邊)。但是,我收到了同樣的錯誤。 – Vahid 2014-10-03 22:21:31

回答

1

當您的主程序在Fortran中時,爲什麼要鏈接g++?以其他方式完成,與gfortran聯繫並添加-lstdc++

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

或者用最新版本的GCC。即使使用原始設置,仍然支持所有GCC版本。