简体   繁体   中英

g++ 4.2.1: -O breaks linking to a templated function

g++ main.c fc below works with g++-4.2.1, but
g++ -O3 main.c fc gives the warning

/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()
}

On macosx 10.4.11 powerpc-apple-darwin8-g++-4.2.1 (GCC) 4.2.1 (Apple Inc. build 5564), -O2 works, -O3 does not.
On macosx 10.7.4 i686-apple-darwin11-llvm-g++-4.2 (from https://github.com/kennethreitz/osx-gcc-installer ),
plain g++ *.c works, g++ -O *.c gives the same ld: Undefined symbols error.
Maybe a bug g++ <-> old /usr/bin/ld ? More likely I've done something stupid ...

Can anyone help, or see if this works on a non-Mac ? Thanks !

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM