GCC:对未使用的函数的奇怪未解决引用
GCC: strange unresolved reference on function which doesn't used
#include <iostream>
struct CL1
{
virtual void fnc1();
virtual void fnc2(); //not defined anywhere
};
void CL1::fnc1(){}
int main() {}
这在 fnc2 上给出了一个未定义的引用错误,但是它没有在任何地方使用。为什么会这样?我尝试在 Visual Studio 上进行,然后链接成功。
gcc 在 link 时默认不删除未使用的符号,
因此,对于具有虚函数的 class,它会生成虚拟 table,
带有指向每个虚函数的指针,并将此 table 移动到 .rodata 部分,
所以你应该收到这样的错误信息:
g++ test10.cpp
/tmp/cc5YTcBb.o:(.rodata._ZTV3CL1[_ZTV3CL1]+0x18): undefined reference to `CL1::fnc2()'
collect2: error: ld returned 1 exit status
您可以启用垃圾回收和 link 时间,但您不会收到
和错误:
$ g++ -O3 -O3 -fdata-sections -ffunction-sections -fipa-pta test10.cpp -Wl,--gc-sections -Wl,-O1 -Wl,--as-needed
$
#include <iostream>
struct CL1
{
virtual void fnc1();
virtual void fnc2(); //not defined anywhere
};
void CL1::fnc1(){}
int main() {}
这在 fnc2 上给出了一个未定义的引用错误,但是它没有在任何地方使用。为什么会这样?我尝试在 Visual Studio 上进行,然后链接成功。
gcc 在 link 时默认不删除未使用的符号, 因此,对于具有虚函数的 class,它会生成虚拟 table, 带有指向每个虚函数的指针,并将此 table 移动到 .rodata 部分, 所以你应该收到这样的错误信息:
g++ test10.cpp
/tmp/cc5YTcBb.o:(.rodata._ZTV3CL1[_ZTV3CL1]+0x18): undefined reference to `CL1::fnc2()'
collect2: error: ld returned 1 exit status
您可以启用垃圾回收和 link 时间,但您不会收到 和错误:
$ g++ -O3 -O3 -fdata-sections -ffunction-sections -fipa-pta test10.cpp -Wl,--gc-sections -Wl,-O1 -Wl,--as-needed
$