链接 C++ 和 Fortran 时出现重复符号

克里斯

链接 fortran 和 C++ 代码时出现重复符号错误,我不知道为什么。

我有以下 fortran 代码simple.f90

module foo
    use iso_c_binding
    integer(kind=c_int) :: bar
end module foo

subroutine print()
    use foo
    write(*,*) bar
end subroutine print

我有以下 C++ 驱动程序 main.cpp


extern "C"
{
  int __foo_MOD_bar;
  void print();
}


int main()
{
  __foo_MOD_bar = 42;
  print();
  return 0;
}

我想要做的是将模块 foo/bar 变量分配给一个值并从 Fortran 子例程中打印它。

但是,当我编译和链接时

gfortran -std=f2003 -fno-underscoring -c simple.f90
g++ -c main.c
gfortran main.o gfortran.o -o out

我收到重复的符号错误

[100%] Linking CXX executable out
duplicate symbol '___foo_MOD_bar' in:
    CMakeFiles/out.dir/main.cpp.o
    CMakeFiles/out.dir/simple.f90.o
ld: 1 duplicate symbol for architecture x86_64
 nm simple.f90.o
00000000000000f8 s EH_frame1
00000000000004cc S ___foo_MOD_bar
                 U __gfortran_st_write
                 U __gfortran_st_write_done
                 U __gfortran_transfer_integer_write
0000000000000000 T _print
0000000000000078 s lC0
nm main.cpp.o
0000000000000388 S ___foo_MOD_bar
0000000000000000 T _main
                 U _print

我有点不知所措

数字零

int __foo_MOD_bar;定义了一个变量而不仅仅是声明它(因为extern "C"块仅更改链接),并且 Fortran 代码大概也是如此。尝试向extern变量本身添加显式说明符,例如:

extern int __foo_MOD_bar;

extern "C" int __foo_MOD_bar;应该在 IIRC 内部或外部也能正常工作extern "C")。

或者,您可以使用 Fortran 部分中的声明替换变量定义,但我不知道该语言,因此无法解释如何。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章