dabadaba
dabadaba

Reputation: 9522

undefined reference for a referenced method

I am getting an undefined reference and I have no clue why, everything looks properly declared and defined and linked, but obviously there is something wrong.

Error:

I am getting undefined reference to UserOrder::add(User&, Order&) called in Order::Order(UserOrder& [...])

order.h:

#include "user-order.h"

class Order {
public:
    Order(UserOrder& [...], User&, [...]);
    [...]
};

order.cpp

Order::Order(UserOrder& u_o [...], User& u, [...]) {
    [...]
    u_o.add(u, *this); // here is the undefined reference
    [...]
}

user-order.h:

#include "user.h"
#include "order.h"
class Order;

class UserOrder {
public:
    [...]
    typedef std::set<Order*> Orders;
    void add(User&, Order&);
    [...]   
private:
    std::map<User*, Orders> orders;
    std::map<Order*, User*> users;
};

user.cpp

UserOrder::add(User& u, Order& o) {
    orders[&u].insert(&o);
    users.insert(make_pair(&o, &u)); 
}

Why the heck am I getting undefined refference for add?

Upvotes: 2

Views: 98

Answers (1)

NirMH
NirMH

Reputation: 4929

You have a cyclic #include scenario.

pay attention...

order.h

#include "user-order.h"

and

user-order.h

#include "order.h"

so the compiler can't know the definition of all your types during the compilation process.

You'll have to redesign your class diagram. As you've have not posted any additional code except from partial method prototypes, i can only suggest you may turn the Order class into a polymorphic base and derive UserOrder from it.

Of course your program might need additional re-factor operations.

EDIT - you can find useful info about how to resolve the circular dependency in the following Resolve circular dependencies in c++ Stack Overflow post

Upvotes: 1

Related Questions