我有一个我认为不应该出现的链接错误:
koala.o:
In function `ns1::utils::io::protocol::InputSequenceFile
<
ns1::utils::io::protocol::TargetSequenceProtocol<
ns1::utils::io::FooIndexTarget
>
, false
>::InputSequenceFile(ns1::utils::io::DataFileDescriptor const&) [clone .constprop.1291]':
koala.cpp:(.text+0x332a):
undefined reference to
`ns1::utils::io::DataFileFactory::createIndexedInputFile
(
ns1::utils::io::DataFileDescriptor const&, ns1::utils::io::IndexMode::Enum, bool
)'
(我只更改了空格以便更容易阅读。我还非常小心地做了一些匿名化。)
然后我使用 nm
发现了关于符号的情况:
nm other.o:
0000000000008f20 t _ZN4ns15utils2io15DataFileFactory22createIndexedInputFileERKNS1_18DataFileDescriptorENS1_9IndexMode4EnumEb.constprop.1677
nm koala.o:
U _ZN4ns15utils2io15DataFileFactory22createIndexedInputFileERKNS1_18DataFileDescriptorENS1_9IndexMode4EnumEb
(grep 输出)
它们是相同的,不包括 constprop.1677
(我不知道它是什么)。有问题的方法是类的静态方法。我需要一些帮助来了解问题的根本原因。
最佳答案
gcc 的 -O3
开关默认打开 -fipa-cp-clone
,添加 -fno-ipa-cp-clone
到命令行禁用。
该开关在编译器中启用控制和到达流分析的相关优化,引入函数的折叠克隆版本,这些函数可以显示为常量值,并且在编译对象中,这些克隆可以通过 .constprop
后缀。
背景
Constant propagation is a well-known global flow analysis problem. The goal of constant propagation is to discover values that are constant on all possible executions of a program and to propagate these constant values as far forward through the program as possible. Expressions whose operands are all constants can be evaluated at compile time and the results propagated further.
Wegman, Mark N; Zadeck, F. Kenneth (April 1991), "Constant Propagation with Conditional Branches", ACM Transactions on Programming Languages and Systems 13 (2): 181–210
这是一个具体的例子:
int foo (int x, int y) {
if (y == 0) return 0;
return foo (x, --y) % 2;
}
int main () {
int z = 0;
for (int i = 0; i < 6; i++) {
z = z + foo (1, i);
}
}
// g++-4.8 -c -O2 -fipa-cp-clone main.cpp && nm main.o
0000000000000030 T _Z3fooii
0000000000000000 t _Z3fooii.constprop.0
0000000000000000 T main
您可以观察到,使用 -fipa-cp-clone
,编译器识别出有一个常量被传递给外部可见的 foo()
方法,并为通过克隆函数进行优化。
( See live here )
关于c++ - C++ 链接错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21936012/