C调用Fortran子例程时gcc链接出现__gfortran_st_close未定义符号如何解决
C语言调用Fortran子例程链接缺失符号问题解决办法
你遇到的报错信息如下:
Undefined symbols for architecture x86_64: "__gfortran_st_close", referenced from: "__gfortran_st_open", referenced from: "__gfortran_st_read", referenced from: "__gfortran_st_read_done", referenced from: "__gfortran_st_rewind", referenced from: "__gfortran_st_write", referenced from: "__gfortran_st_write_done", referenced from: "__gfortran_stop_string", referenced from: "__gfortran_transfer_array", referenced from: "__gfortran_transfer_character_write", referenced from: "__gfortran_transfer_real", referenced from: ld: symbol(s) not found for architecture x86_64 clang: error: linker command failed with exit code 1 (use -v to see invocation)
以上所有__gfortran_开头的缺失符号都属于GNU Fortran运行时库libgfortran,你用gcc做链接时没有主动关联该库,才会触发该错误。
解决方法
- 方法1:链接阶段添加
-lgfortran参数
原有链接命令格式如下:
调整后:gcc c_main.o fortran_sub.o -o target_programgcc c_main.o fortran_sub.o -o target_program -lgfortran - 方法2:添加库路径后再链接
如果执行方法1后仍然提示找不到库,说明gcc没有搜索到libgfortran的安装位置,先找到libgfortran.so(Linux)或libgfortran.dylib(macOS)的所在路径,用-L参数指定路径后再链接,示例:gcc c_main.o fortran_sub.o -o target_program -L/path/to/your/gfortran/lib -lgfortran - 方法3:直接用gfortran执行链接步骤
gfortran会自动加载Fortran运行时库依赖,无需手动指定参数,命令如下:gfortran c_main.o fortran_sub.o -o target_program
注意事项
你当前环境的gcc实际是clang伪装版本(报错末尾有clang标识),需要确保安装的gfortran架构与当前系统架构匹配,x86_64架构不要安装ARM版本的gfortran工具链,否则仍然会提示架构不匹配的符号缺失错误。
内容的提问来源于stack exchange,提问作者Grateful_for_stackoverflow
相关产品推荐
相关产品推荐

