Link errors while using G++ for MPI code

空扰寡人 提交于 2019-12-24 15:24:48

问题


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


回答1:


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



来源:https://stackoverflow.com/questions/6451340/link-errors-while-using-g-for-mpi-code

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!