Avihai Marchiano
Avihai Marchiano

Reputation: 3927

c++ why definition of static member is not always required?

I read this good post (on undefined-reference-to-a-static-member), but i from what i can see i dont always required to defined the static member in the cpp. So i am asking for help to understand the rules.

several examples - all examples without def in the cpp. In the h file for class Master declaration is :

class Master{
public:
    static IDataSynchronization& sync_data_cb_;
}

In cpp:

void Master::start(IDataSynchronization& syncDataCB);   - error for undefined
void Master::start(int p,IDataSynchronization& syncDataCB);  no error

//Here is use in the static sync_data_cb_ void Master::sendData(){ list data = sync_data_cb_.syncData(); list::iterator it; for (it = data.begin(); it != data.end(); ++it) { sendto(instance_->data_sock_fd_, (*it).c_str(), (*it).length(), 0,(const struct sockaddr *) &instance_->target_host_data_, instance_->sockadd_length_);

    }
}

for this class:

class Logger {
public:
    static void Log(const char *format, ...);
private:
    static FILE* file_;
    static mutex mtx_;
};

If in another classes that i declared static static FILE* (and used it in the class methods) i dont getting an error for undefined it.

I am using in these static memners in all cases.

Can anyone clear the ruled for me?

Thank you

Upvotes: 0

Views: 219

Answers (2)

user743382
user743382

Reputation:

The rules say you need a definition of syncDataCB if you use it. "If you use it" is defined differently formally, but this is close enough for understanding.

If you do use it without a definition, though, the compiler/linker isn't required to give an error. In practice that would mean that if you pass sync_data_cb_ to start, but don't use syncDataCB there, you won't get an error if start gets inlined, but will if it doesn't.

The fact that you won't always get an error message isn't relevant, it doesn't mean that the code is sometimes correct. If you use sync_data_cb_, you need a definition.

Upvotes: 4

Like with many other things, only symbols that are actually used (odr-used in C++11 parlance) need to be defined.

You can have declarations for many more things that you need, and as long as they are not used you won't need a definition.

Upvotes: 0

Related Questions