Go应用cgo调用Fortran:升级gfortran后参数秩不匹配及编译旗标问题
Why -fallow-argument-mismatch is rejected by cgo
cgo validates flags passed via #cgo FFLAGS to avoid unsafe or compiler-specific options that could break cross-compilation or introduce unexpected behavior. The -fallow-argument-mismatch flag relaxes Fortran's strict argument rank/type checking, which cgo classifies as an invalid flag for its FFLAGS directive. Setting FFLAGS or FCFLAGS environment variables also doesn't work because cgo overrides or filters these when processing its own directives.
Alternative Solutions
1. Use a Fortran compiler wrapper script
Create a wrapper script that injects the -fallow-argument-mismatch flag into every gfortran call, then tell cgo to use this wrapper instead of the default gfortran:
- Create a script named
gfortran-wrapper.shwith:#!/bin/bash exec gfortran -fallow-argument-mismatch "$@" - Make it executable:
chmod +x gfortran-wrapper.sh - Build your Go app using this wrapper as the Fortran compiler:
FC=/path/to/gfortran-wrapper.sh go build
This works because cgo calls the wrapper script, which adds the required flag without triggering cgo's flag validation.
2. Precompile Fortran code into a static library
Compile your Fortran files separately with the -fallow-argument-mismatch flag, then link the resulting static library into your Go app via cgo:
- Compile Fortran source files to object files:
gfortran -c -fallow-argument-mismatch somdec.f90 [other-fortran-files].f90 - Create a static library from the object files:
ar rcs libfortran.a somdec.o [other-object-files].o - In your Go code's cgo section, link against the static library:
/* #cgo LDFLAGS: -L. -lfortran -lgfortran #include "somdec.h" // Adjust to your Fortran header file */ import "C" - Build your app normally:
go build
This approach isolates the Fortran compilation step from cgo, letting you use the flag directly with gfortran.
3. Temporary workaround: Use CGO_FCFLAGS (if applicable)
Some versions of cgo may respect the CGO_FCFLAGS environment variable for Fortran compiler flags, though this isn't officially documented. Try setting it before building:
CGO_FCFLAGS="-fallow-argument-mismatch" go build
Note: This may not work in all Go versions, as cgo's handling of Fortran flags can vary.
内容的提问来源于stack exchange,提问作者Marty Farce

