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:
- You are linking with a static library
libfoo.a
. libfoo.a
containsfoo.o
that containsSW_Agent_PP::SW_Agent_PP()
and a bunch of other functions.- Another library
libbar.a
, listed afterlibfoo.a
in the link line, uses a bunch of other functions fromlibfoo.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.
精彩评论