Unnamed/anonymous namespaces vs. static functions

后端 未结 11 2001
一个人的身影
一个人的身影 2020-11-22 03:27

A feature of C++ is the ability to create unnamed (anonymous) namespaces, like so:

namespace {
    int cannotAccessOutsideThisFile() { ... }
} // namespace
<         


        
11条回答
  •  遇见更好的自我
    2020-11-22 03:58

    A compiler specific difference between anonymous namespaces and static functions can be seen compiling the following code.

    #include 
    
    namespace
    {
        void unreferenced()
        {
            std::cout << "Unreferenced";
        }
    
        void referenced()
        {
            std::cout << "Referenced";
        }
    }
    
    static void static_unreferenced()
    {
        std::cout << "Unreferenced";
    }
    
    static void static_referenced()
    {
        std::cout << "Referenced";
    }
    
    int main()
    {
        referenced();
        static_referenced();
        return 0;
    }
    

    Compiling this code with VS 2017 (specifying the level 4 warning flag /W4 to enable warning C4505: unreferenced local function has been removed) and gcc 4.9 with the -Wunused-function or -Wall flag shows that VS 2017 will only produce a warning for the unused static function. gcc 4.9 and higher, as well as clang 3.3 and higher, will produce warnings for the unreferenced function in the namespace and also a warning for the unused static function.

    Live demo of gcc 4.9 and MSVC 2017

提交回复
热议问题