title: Link errors while using G++ for MPI code
body: <p>My code is as simple as this:</p>
  
  <pre><code>#include &lt;mpi.h&gt;
  int main(int argc, char**args) {
      MPI_Init(&amp;argc, &amp;args);
      int mpiSize;
      int mpiRank;
      MPI_Comm_size(MPI_COMM_WORLD, &amp;mpiSize);
      MPI_Comm_rank(MPI_COMM_WORLD, &amp;mpiRank);
      MPI_Finalize();
  }
  </code></pre>
  
  <p>I first compile it to object file:</p>
  
  <pre><code>g++ -c src/mpitest.cpp -o src/mpitest.o
  </code></pre>
  
  <p>Then I can easily use mpicxx:</p>
  
  <pre><code>mpicxx src/mpitest.o -o mpi
  </code></pre>
  
  <p>But I want to use g++ instead, because It's easier for automake, so I tried:</p>
  
  <pre><code>mpicxx src/mpitest.o -o mpi -show
  </code></pre>
  
  <p>It prints out:</p>
  
  <pre><code>g++ src/mpitest.o -o mpi -I/usr/local/include -L/usr/local/lib -L/usr/local/lib -lmpichcxx -lmpich -lopa -lpthread -lrt
  </code></pre>
  
  <p>And yes, that command actually does the same thing successfully. However, If I tried to change it to (I just change the object file and output to the end):</p>
  
  <pre><code>g++ -I/usr/local/include -L/usr/local/lib -L/usr/local/lib -lmpichcxx -lmpich -lopa -lpthread -lrt src/mpitest.o -o mpi
  </code></pre>
  
  <p>Which is what automake does when it adds LDFLAGS, the g++ start complaining...</p>
  
  <pre><code>src/mpitest.o: In function `main':
  ..src/mpitest.cpp:5: undefined reference to `MPI_Init'
  ../src/mpitest.cpp:8: undefined reference to `MPI_Comm_size'
  ../src/mpitest.cpp:9: undefined reference to `MPI_Comm_rank'
  ../src/mpitest.cpp:10: undefined reference to `MPI_Finalize'
  collect2: ld returned 1 exit status
  </code></pre>
  
  <p>What happens with g++ ? I couldn't figure out. Please enlighten me. Why the order here matter at all ? What is the proper way to do what I want from the beginning ?</p>
  
  <p>Thanks a lot</p>
  
  <p>p/s : g++ --version
  g++ (Ubuntu 4.4.3-4ubuntu5) 4.4.3
  mpi is mvapich2</p>