title: Automatic Ordering of Object Files "*.o" in a Fortran Makefile
body: <p>Here I have two Fortran90 files and a makefile:</p>
  
  <p><em>Contents of file</em> <strong>main_mod.f90</strong>:</p>
  
  <pre><code>module main_mod
  
  contains
  
    subroutine add(a, b)
      implicit none
      integer, intent(in) :: a, b
      print *, (a+b)
    end subroutine add
  
  end module main_mod
  </code></pre>
  
  <p><em>contents of file</em> <strong>main_mod2.f90</strong></p>
  
  <pre><code>module main_mod2
    use main_mod
  
  contains
  
    subroutine add2(a, b)
      implicit none
      integer, intent(in) :: a, b
  
      call add(a, b)
    end subroutine add2
  
  end module main_mod2
  </code></pre>
  
  <p>and in <strong>makefile</strong>, I automatically generate a list of ".o" files from current directory: </p>
  
  <pre><code>F90 = /usr/bin/gfortran
  COMPFLAGS    =  -c
  %.o: %.f90
          $(F90) $(COMPFLAGS) $*.f90
  
  all: $(patsubst %.f90,%.o,$(wildcard *.f90))
  </code></pre>
  
  <p>when I make the project, the wildcard statement in my make file generates a list of object files like:</p>
  
  <pre><code>main_mod2.o main_mod.o
  </code></pre>
  
  <p>and then the compilation fails because first, the file <em>main_mod.f90</em> needs be compiled which would give us <em>main_mod.o</em> and <em>main_mod.mod</em> used in <em>main_mod2.f90</em>. Then <em>main_mod2.f90</em> would be compiled successfully. That means the permutation of object files must be: </p>
  
  <pre><code>main_mod.o main_mod2.o
  </code></pre>
  
  <p>Now, the question is, in general case when I create the list of object files using wildcard, how can I enforce correct permutation of object files?</p>