Shoud Do I use unnamed namespaces in the implementation files?

I defined some functions (classes are not involved here) in an external * .cpp file, and, of course, there is a corresponding * .h file.

Some of the functions in the * .cpp file are no longer used in this * .cpp file. They are not even mentioned in the * .h file.

Should I put these functions in an unnamed namespace or can they live next to other functions? And if so, why do I need an unnamed namespace? I do not see a problem, since these functions are not accessible from the outside.

+5
source share
3 answers

, , . , - .

:

// library.cpp

// a "private" function here, in that it is not declared anywhere
void f() {}

namespace
{
   // same as above, except within an anonymous namespace
   void g() {}
}

// client.cpp

void f();

int main()
{
   // Can call f(), it been declared and is now effectively "public"
   f();

   // compilation error, this has no idea what g() is, it not declared 
   // in any scope that can be resolved here
   g();

   return 0;
}
+9

:

1. " ?"

: , :

//============================
// Filename: "mylibrary.hpp"
//============================
// Description:
// Utility functions.
//============================
#ifndef MYLIBRARY_H_INCLUDED
#define MYLIBRARY_H_INCLUDED
//============================

namespace MyLibrary
{
    void DoSomething();
} // namespace MyLibrary

//============================
#endif // MYLIBRARY_H_INCLUDED
//============================

:

//============================
// Filename: "mylibrary.cpp"
//============================
// Description:
// Utility functions.
//============================
// self header include
#include "mylibrary.hpp"
//============================

namespace MyLibrary
{
    void DoSomethingBefore()
    {
      // ...
    }

    void DoSomethingAfter()
    {
      // ...
    }

    void DoSomethingConfirmed()
    {
      // ...
    }

    void DoSomething()
    {
      DoSomethingBefore();
      DoSomethingConfirmed();
      DoSomethingAfter();
    }
} // namespace MyLibrary

//============================
#endif // MYLIBRARY_H_INCLUDED
//============================

, "mylibrary.o" "mylibrary.obj". : "mylibrary.hpp" "mylibrary.obj", "mylibrary.cpp". "plain c" / "++" .

, .

2. " , ?"

" " - .

:

/

, , , "" .

- , , , " c" "++" . " " " " .

-, , .

3

(a) , , . . . , .

(b) . , .

(c) , , ".h" ".hpp", ++. , ++ "++" , .

.

+4

I think if you do not want these functions to be visible from the outside, declare them as static.

+1
source

All Articles