Namespace Scope functions and the static keyword in CLI

D

DaTurk

Hi,

I have an interesting issue, well, it's not really an issue, but I'd
like to understand the mechanics of what's going on. I have a file,
in CLI, which has a class declared, and a static fuction. Because the
class is declared globally, I declare it as static.

Is a function with a namespace scope declared as static by default?

So, this worked fine when I was accessing the static function inside
the cpp file paired with this header. Keep in mind that it is
declared static explicitly.

But when I ty to access this static function from another file, aside
from the cpp file the class is implemented in, I get an compile error
C2129 function declared but not defined. But when declare it as
static inline, or remove the static keyword it works fine.

Can someone explain why this is?
 
D

David Lowndes

But when I ty to access this static function from another file, aside
from the cpp file the class is implemented in, I get an compile error

when applied to a global function, the static keyword limits the scope
to the current source module, so an error in that circumstance is to
be expected.
But when declare it as
static inline, or remove the static keyword it works fine.

If you define it inline (in the header file), both source modules will
have a copy of the code.

Dave
 
B

Ben Voigt

David Lowndes said:
when applied to a global function, the static keyword limits the scope
to the current source module, so an error in that circumstance is to
be expected.

And because this behavior is inconsistent with other uses of static, it's
now recommended to use the anonymous namespace for that instead.

Without the static keyword, you should have gotten a multiple definition
error.
If you define it inline (in the header file), both source modules will
have a copy of the code.

Inline functions should be defined in the header file, non-inline function
should have a prototype in the header, but the definition should always be
in an implementation file. This is based on your use of the inline keyword
(or defining inside the type declaration), not the compiler's ultimate
decision whether to inline or not.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top