Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declare and define static variable in C++ header?

Many other questions deal with how to allocate a variable by declaring it in a header file and defining it (allocating) in a .cpp file.

What I want to do is not use any .cpp files for my class, and to define all functions as inline (in the header file). The problem that I run into is how to define static member variables so that even when the .h file is included in multiple compilation units I don't get the "first defined here" linker error.

I'm open to preprocessor hacks, etc. if it gets the job done. I just want to avoid any .cpp files.

If it matters I'm using GCC.

like image 220
srlm Avatar asked Aug 03 '13 10:08

srlm


People also ask

Can we declare static variable in header file in C?

Yes there is difference between declaring a static variable as global and local. If it is local, it can be accessed only in the function where it's declared. But if it is global, all functions can access it.

What happens if u define static member variable in header file?

It will be considered as a global static variable. It will limit its scope within that file in which that header file has been included. Generally, we should not use it because whoever will include that header file in any number of source code, it will create separate variable copy for each source file.

Can we initialize static variable in header file?

When a static value is used to initialize another static variable, the first may not be initialized, yet. // file. h class File { public: static struct _Extensions { const std::string h{ ". h" }; const std::string hpp{ ".


1 Answers

You can abuse the singleton pattern if you really must avoid any .cpp files:

class Foo {
    public:
        static Bar& getMyStatic() {
            static Bar bar;
            return bar;
        };
};

This works because now the variable is a static variable inside a function, and static has a different meaning within a function context than within a class context. And for functions, the linker does recognize multiple identical definitions and throws away the copies.

But, of course, I would strongly advise against avoiding .cpp files: It means that you get into a situation where you have to build the entire program, or at least large parts of it, in one big piece. Every change you do will necessitate a complete rebuilt which slows down your change-compile-test cycle significantly. For very small projects that might not be a problem, but it is for medium to large ones.

like image 116
cmaster - reinstate monica Avatar answered Sep 17 '22 23:09

cmaster - reinstate monica