1

g++ main.c f.c下面适用于 g++-4.2.1,但
g++ -O3 main.c f.c会发出警告

/usr/libexec/gcc/powerpc-apple-darwin8/4.2.1/ld: Undefined symbols:
int f<int>(int const*)
collect2: ld returned 1 exit status


// main.c
template <typename T>
int f( const T* A );

int main()
{
    int* A = new int[10];
    int ftemplate = f( A );
}


// f.c
template <typename T>
int f( const T* A )
{   return A[0];
}

int call_f()
{   int* A = new int[10];
    return f( A );  // ok here but not from main()
}

在 macosx 10.4.11 powerpc-apple-darwin8-g++-4.2.1 (GCC) 4.2.1 (Apple Inc. build 5564) 上, -O2有效,-O3无效。
在 macosx 10.7.4 i686-apple-darwin11-llvm-g++-4.2 (来自https://github.com/kennethreitz/osx-gcc-installer)上,
普通的g++ *.c作品,g++ -O *.c给出了同样的ld: Undefined symbols错误。
也许是一个错误 g++ <-> old /usr/bin/ld ?更有可能我做了一些愚蠢的事情......

谁能帮忙,或者看看这是否适用于非Mac?谢谢 !

4

1 回答 1

1

Unless you explicitly instantiate a function template for the arguments you use in a function call, you have to make the function template definition visible to the caller of it.

This includes the call in main.

It probably works in unoptimized builds because the compiler emits an exported function definition symbol for the implicit function template instantiation. The C++ Standard grants compilers to omit doing that, and GCC does it here for optimized builds (probably it just inlines the call and then the definitions symbol becomes unused).

于 2012-11-20T20:08:59.077 回答