开发者

Weird 'undefined reference' error

I have run into a peculiar error in a C++ project at work.

I have found a fix, but I am now really satisfied, as I would like to understand what actually causes the error.

When building this snippet of code:

#include <iostream>
#include "snmp/snmp/SW_SNMP_Values.hpp"
#include "snmp/agent/SW_Agent.hpp"
#include "snmp/agent/SW_Agent_PP.hpp"

int main()
{
    //SW_Agent_PP agent;

    return 0;
}

Notice t开发者_如何学Gohat SW_Agent_PP is COMMENTED OUT!! When building this, I get a ton of undefined reference errors, for classes that are in use by the SW_Agent_PP object.

The FIX is to ACTUALLY CREATE THE OBJECT! so if I do this:

#include <iostream>
#include "snmp/snmp/SW_SNMP_Values.hpp"
#include "snmp/agent/SW_Agent.hpp"
#include "snmp/agent/SW_Agent_PP.hpp"

int main()
{
    SW_Agent_PP agent;

    return 0;
}

everything works fine and dandy.

How can I get linker errors for NOT using something? I would like to hear if anyone have run into similar experiences before, and if they found what caused it.

I am sorry, but I cannot release more code as it is company property. Many thanks in advance!


Linkers are complicated and this behaviour is by no means unusual. Here's one possible explanation:

  1. You are linking with a static library libfoo.a.
  2. libfoo.a contains foo.o that contains SW_Agent_PP::SW_Agent_PP() and a bunch of other functions.
  3. Another library libbar.a, listed after libfoo.a in the link line, uses a bunch of other functions from libfoo.a.

The linker processes static libraries in order and never goes back. Therefore the references in libbar.a can be only satisfied if corresponding object was pulled from libfoo.a by main().

The solution is to reorder the libraries in the link line.

There are other possible explanations. It's hard to tell without seeing actual code.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜