You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Windows下MinGW+Make构建Fortran项目的依赖问题及解决方案

Windows下MinGW+Make编译Fortran的依赖问题解决方案

背景与问题

在Windows环境使用MinGW的gfortran编译器和make工具编译Fortran代码时,源文件分为两类:

  • .f:普通Fortran源文件
  • .for:模块文件(部分文件包含多个模块)

原通用Makefile存在两个依赖处理缺陷:

  • 修改.for模块文件后,依赖该模块的.f文件无法自动触发重编译
  • 当.f文件通过include 'bar.inc'引入头文件时,修改bar.inc后,对应的.f文件不会自动重编译

改进版Makefile

以下是同时适配模块依赖与INCLUDE文件依赖的Makefile:

# Source directories
dirs := . srkf

# Executable to create
Executable = D:\Executables\a.exe
# -------------------------------------------------------

# Obj dir
Objets_dir ?= ../obj

VPATH = $(dirs) $(Objets_dir)

# Creation of .for list
Sourmod := $(foreach dir,$(dirs),$(wildcard $(dir)/*.for))

# Creation of .f list
Sources := $(foreach dir,$(dirs),$(wildcard $(dir)/*.f))

# Obj list
Objmod = $(patsubst %.for,%.o,$(Sourmod))
Objets = $(patsubst %.f,%.o,$(Sources))

# Full path to .o
TempObjets = $(addprefix $(Objets_dir)/, $(notdir $(Objmod) $(Objets)))
DEPENDS = $(patsubst %.o,%.d,$(TempObjets))

# Comp options
cpl = gfortran
FFLAGS = -ffpe-trap=invalid,zero,overflow -O3 -Wall
lnk = gfortran
lnk_opt = 

all: $(Executable)

# Compilation
$(Objets_dir)/%.o:%.for
    $(cpl) -J$(Objets_dir) $(FFLAGS) -c $< -o $@

$(Objets_dir)/%.o:%.f
    $(cpl) -I$(Objets_dir) $(FFLAGS) -c $< -o $@

$(Objets_dir)/%.d: %.for
    @-(echo -n $(Objets_dir)/;$(cpl) -cpp -MM -J$(Objets_dir) -fsyntax-only $(FFLAGS) -c $<) > $@

$(Objets_dir)/%.d: %.f
    @-(echo -n $(Objets_dir)/;$(cpl) -cpp -MM -I$(Objets_dir) -fsyntax-only $(FFLAGS) -c $<) > $@

-include $(DEPENDS)

# Link
$(Executable): $(TempObjets)
    $(lnk) $(lnk_opt) -o $@ $^

# Clean
clean:
    @-rm -rf $(Objets_dir)/* $(Executable)

#all:
#   @echo $(value Sources)
#   @echo $(value Objets)
#   @echo $(value TempObjets)

效果验证

经测试,该Makefile可解决上述两类问题:

  • 修改bar.inc等INCLUDE文件后,依赖它的.f文件会自动触发重编译
  • 修改.for模块文件后,仅当生成的.mod文件内容发生变化时,依赖该模块的.f文件才会重编译,gfortran的这一智能处理表现超出预期

内容的提问来源于stack exchange,提问作者Parker Lewis

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 19:53:13