Can we define static variable header file


















If you declare a static variable at file level i. Number two is the important one here. When you compile a single file, such as main. But when you compile more than one.

A static variable is only available to a single translation unit. If you include the same variable in another unit, you will effectively have two variables with the same name. From a draft of the C specification :. If the declaration of an identifier for an object has file scope and no storage-class specifier, its linkage is external. Objects declared const and not explicitly declared extern have internal linkage.

You can easily test this with a small code sample:. So, using static has no effect. The static declaration at this level of code means that the variabel is only visible in the current compilation unit. This means that only code within that module will see that variable.

There will be N copies of that variable for the N places that header is included. They are not related to each other at all. Any code within any of those source files will only reference the variable that is declared within that module. VAL will always be defined separately in every file that includes the header. In C, file-scoped variables are extern by default.

You also need to take account of the fact that both variables are designated const. Ideally the compiler would always choose to inline these variables and not include any storage for them. The declaration that Jeremy gave in the. That is why, even if that static variable were declared private, the "external" declaration could still be used to initialize the variable. In other words, that class could have been defined as:.

I tried this and it actually does work. You two guys probably already know this, but it's news to me. Otherwise you will get linker errors. The issue is that this static variable needs to be living in exactly one of the generated object files or the linker will complain about multiple or missing definitions.

The object file containing the instanciation will be that home. So if you put it into a header file and include that into several other files you get several homes for that variable.

Qt Forum.



0コメント

  • 1000 / 1000