user2269707
user2269707

Reputation:

Any way I can define and declare an extern object in header?

I'm writing a library which is totally base on templates, so I don't have any cpp files. Now I want to declare an global variable, then I realize I have nowhere to go.

If I simply declared it in header, I will got a "multiple definition" error, if I use extern, I have to create a cpp file to really declare it.

So is there any way I can declare a global variable in header?

P.S. since a static member in a template class can (only) be declared in header, how it works?

Upvotes: 2

Views: 91

Answers (2)

Denis Sheremet
Denis Sheremet

Reputation: 2583

As @M.M mentioned, you can use inline declaration if you're on C++17 or above.

Hovever, if that's not the case, you can declare inline function which returns a reference to static variable, just like that:

inline int& getData() {
    static int data;
    return data;
}

Then, in your .cpp file (as well as in any function body inside your headers) you can simply call it like int& data = getData().

As a side note, if you want to ensure that global object is created only once and is not copied by accident, it could suit you better to use a signleton instead. Global variables are more of a c-style and not really considered a good practice in c++.

Upvotes: 0

TruthSeeker
TruthSeeker

Reputation: 1579

You can use macro to for single declaration,

#ifndef __usermacro
#define __usermacro
//Declare global variable
#else
//Declare extern 
#endif

Upvotes: 1

Related Questions