简体   繁体   English

g ++ 4.2.1:-O中断到模板函数的链接

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

g++ main.c fc below works with g++-4.2.1, but g++ main.c fc可与g ++-4.2.1一起使用,但
g++ -O3 main.c fc gives the warning g++ -O3 main.c fc发出警告

/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. 在macosx 10.4.11 powerpc-apple-darwin8-g ++-4.2.1(GCC)4.2.1(Apple Inc.内部版本5564)上, -O2有效, -O3不可用。
On macosx 10.7.4 i686-apple-darwin11-llvm-g++-4.2 (from https://github.com/kennethreitz/osx-gcc-installer ), 在macosx 10.7.4 i686-apple-darwin11-llvm-g ++-4.2(来自https://github.com/kennethreitz/osx-gcc-installer )上,
plain g++ *.c works, g++ -O *.c gives the same ld: Undefined symbols error. 普通的g++ *.c起作用, g++ -O *.c给出相同的ld: Undefined symbols错误。
Maybe a bug g++ <-> old /usr/bin/ld ? 也许是g ++ <->旧的/ usr / bin / ld错误? More likely I've done something stupid ... 我更有可能做了一些愚蠢的事情...

Can anyone help, or see if this works on a non-Mac ? 谁能帮忙,或者看看这是否适用于非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. 这包括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). C ++ Standard允许编译器省略此操作,而GCC在这里这样做是为了优化构建(可能只是内联了调用,然后未使用定义符号)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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