Alex
Alex

Reputation: 360

undefined reference to public methods/variables of a class

I am new to C++. I have a linker problem between 2 files F1 and F2. In order to be more readable, I rewrote the code and output.

F1.h:

class MYCLASS...
   public:....// [constructor] etc         
         void myMethod(const string& r);
         static string s;

F1.cpp:

void myMethod(const string& r)
{
    MYCLASS::s=r;
}
[...]
void serialize(...)
{
   operation(s,...)
}

F2.cpp:

const string& a;
MYCLASS Obj;
Obj.myMethod(a);

The goal is to use the string a from F2.cpp inside the serialize method from F1.cpp, without adding any argument to the serialize function. For that, I am trying to use the intermediate r variable.

The compilation (compiler based on gcc) gives the errors:

In function `the_function_from_F2.cpp(...)':
F2.cpp:227: undefined reference to `MYCLASS::myMethod(std::basic_string<char,      std::char_traits<char>, std::allocator<char> > const&)'
: In function `myMethod(std::basic_string<char, std::char_traits<char>,   std::allocator<char> > const&)':
F1.cpp:197: undefined reference to `MYCLASS::s'
: In function `MYCLASS::serialize(....) const':
F2.cpp:69: undefined reference to `MYCLASS::s'

Thank you for any suggestion !

Upvotes: 0

Views: 151

Answers (2)

dornhege
dornhege

Reputation: 1500

Change to:

void MYCLASS::myMethod(const string& r)
{
    MYCLASS::s=r;
}

std::string MYCLASS::s;

This is still a class method, so you need to specify that.

Upvotes: 1

Some programmer dude
Some programmer dude

Reputation: 409166

You forgot to actually define the MYCLASS::s member. It has to be done in a source file like

std::string MYCLASS::s;

What you are doing in the class is only declaring the static variable.

Upvotes: 1

Related Questions