我使用显式实例化技术编写了一个简单的 C++ 程序,如下所示:
// foo.hpp
#include <iostream>
struct foo
{
template <typename Arg>
static void call(Arg arg)
{
std::cout << "foo\n";
}
};
这里我有类 foo 的显式实例化:
// foo.cc
#include "foo.hpp"
template void foo::call(int);
在主文件中,我使用extern关键字告诉编译器foo::call已经实例化,因此无需再次编译:
// main.cc
#include <iostream>
#include "foo.hpp"
extern template void foo::call(int);
int main(int argc, char const *argv[])
{
foo::call(1);
return 0;
}
我使用gcc-4.9使用g++和mpic++测试程序。对于g++,当我通过foo.o时它工作正常:
g++ -std=c++11 -c foo.cc
g++ -std=c++11 main.cc foo.o -o main
当我没有通过foo.o时,它会按预期抱怨:
g++ -std=c++11 test_simple.cc -o test_simple
/tmp/ccclcKnc.o: In function `main':
test_simple.cc:(.text+0x15): undefined reference to `void foo::call<int>
(int)'
collect2: error: ld returned 1 exit status
但是当我在这两种情况下(通过或不通过foo.o )使用mpic++ (MPICH)编译时,程序编译时应该会抱怨foo.o没有通过。
mpic++ -std=c++11 -c foo.cc
mpic++ -std=c++11 main.cc foo.o -o main
或者
mpic++ -std=c++11 main.cc -o main // this line shouldn't compile but it does
我用OpenMPI测试了代码,行为与g++相同。所以问题是为什么MPICH会忽略extern并再次编译实例化。
谢谢,