Denis
Denis

Reputation: 3082

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

This gives an undefined reference error on fnc2, however it isn't used anywhere. Why is this happening? I tried to do it on Visual Studio and then it's linked successfully.

Upvotes: 0

Views: 399

Answers (1)

fghj
fghj

Reputation: 9404

gcc does not remove not used symbols by default at link time, so for your class with virtual functions, it generate virtual table, with pointers to each virtual function, and move this table to .rodata section, so you should receive such error message:

g++ test10.cpp
/tmp/cc5YTcBb.o:(.rodata._ZTV3CL1[_ZTV3CL1]+0x18): undefined reference to `CL1::fnc2()'
collect2: error: ld returned 1 exit status

You can enable garbage collection and link time, and you not receive and errors:

$ g++ -O3 -O3 -fdata-sections -ffunction-sections -fipa-pta test10.cpp -Wl,--gc-sections -Wl,-O1 -Wl,--as-needed
$

Upvotes: 1

Related Questions