Search code examples
c++cmakecompilation

How to create a truly static variable with CMAKE compilation?


In the following macro:

#define REGISTER_CLASS(CLASSNAME) struct CLASSNAME; \
    static bool CLASSNAME##registered = \
    (\
        (Register<CLASSNAME>()), \
        true \
    );

The class is registered correctly with the register function if used before a class. However, if we have inheritance such as:

REGISTER_CLASS(Foo)
class Foo
{
    // ...
};

// Another file:

REGISTER_CLASS(FooBar1)
class FooBar1: public Foo 
{
    // ...
};

// Another file:

REGISTER_CLASS(FooBar2)
class FooBar2: public Foo 
{
    // ...
};

The Foo class is registered multiple times, despite Fooregistered being a static variable. Now, what makes this weird, is that when I compile this code without cmake, we get correct behavior:

https://onlinegdb.com/WsxMOrncf


Solution

  • The Fooregistered variable must be inline to merge the copies of the variable across translation units.