w00d
w00d

Reputation: 5596

Link errors while using G++ for MPI code

My code is as simple as this:

#include <mpi.h>
int main(int argc, char**args) {
    MPI_Init(&argc, &args);
    int mpiSize;
    int mpiRank;
    MPI_Comm_size(MPI_COMM_WORLD, &mpiSize);
    MPI_Comm_rank(MPI_COMM_WORLD, &mpiRank);
    MPI_Finalize();
}

I first compile it to object file:

g++ -c src/mpitest.cpp -o src/mpitest.o

Then I can easily use mpicxx:

mpicxx src/mpitest.o -o mpi

But I want to use g++ instead, because It's easier for automake, so I tried:

mpicxx src/mpitest.o -o mpi -show

It prints out:

g++ src/mpitest.o -o mpi -I/usr/local/include -L/usr/local/lib -L/usr/local/lib -lmpichcxx -lmpich -lopa -lpthread -lrt

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):

g++ -I/usr/local/include -L/usr/local/lib -L/usr/local/lib -lmpichcxx -lmpich -lopa -lpthread -lrt src/mpitest.o -o mpi

Which is what automake does when it adds LDFLAGS, the g++ start complaining...

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

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 ?

Thanks a lot

p/s : g++ --version g++ (Ubuntu 4.4.3-4ubuntu5) 4.4.3 mpi is mvapich2

Upvotes: 1

Views: 5518

Answers (1)

LeleDumbo
LeleDumbo

Reputation: 9340

I didn't really remember, maybe since version 4, library to link with -l must be passed after all source and object files.

Upvotes: 1

Related Questions