Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Using static results in an undefined reference in this piece of code

This is a MSVP of a problem I am facing.
What is wrong with m_eventQueue being static in the code below ?
When it is not static, it compiles fine. I want it to be static because I am planning to use it in another class as well and it is a common queue between them.

This is the error I get

badri@badri-All-Series:~/progs$ g++ --std=c++11 inher3.cpp 
/tmp/ccGTVi2d.o: In function `RecordingConfigJobStateSignal::RecordingConfigJobStateSignal(std::shared_ptr<EventQueue> const&)':
inher3.cpp:(.text+0x13c): undefined reference to `commonQueue::m_eventQueue'
collect2: error: ld returned 1 exit status

This is inher3.hpp

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

#include<iostream>
#include<memory>
#include<queue>
using namespace std;
class EventBase
{
public:

private:
        int a;
};
using EventBasePtr = std::shared_ptr<EventBase>;

class SubscriptionManager
{

        public:
                int x;
};

class EventQueue
{
public:
    explicit EventQueue( SubscriptionManager& ){};
    ~EventQueue();
private:
    std::queue< EventBasePtr >          m_queue;
};
using EventQueuePtr = std::shared_ptr<EventQueue>;


class commonQueue
{
        public:             
                int *a;
                static std::queue< EventBasePtr >       m_queue;
                static EventQueuePtr m_eventQueue;
};

class RecordingConfigJobStateSignal: public commonQueue
{
        public:
                int c;
                RecordingConfigJobStateSignal( const EventQueuePtr &);
        private:
                int b;

};

This is inher3.cpp

#include<iostream>
#include"inher3.hpp"

RecordingConfigJobStateSignal::RecordingConfigJobStateSignal( const EventQueuePtr& eventQueue )//:m_eventQueue( eventQueue )
{
        /* m_eventQueue is actually from class commonQueue */
        m_eventQueue = eventQueue;
}

int main()
{
        return 0;
}


>Solution :

When you declare a static member in a class, C++ requires you to define the member outside of the class explicitly. Put this outside of your class in the .cpp file:

/*static*/
EventQueuePtr commonQueue::m_eventQueue;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading