C++ static local function vs global function

后端 未结 4 1647
一整个雨季
一整个雨季 2021-01-31 08:13

What is the utility of having static functions in a file ?

How are they different from having global functions in a file ?

static int Square(int i)
{
            


        
4条回答
  •  爱一瞬间的悲伤
    2021-01-31 08:50

    A static function simply means that the linker cannot export the function (i.e. make it visible to other translation units). It makes the function "private" to the current translation unit. It is the same as wrapping the function in an anonymous namespace.

    namespace {
    
        int Square(int i)
        {
           return i * i;
        } 
    
    }
    

    Generally, using an anonymous namespace is the preferred C++ way of achieving this, instead of using the static keyword.

提交回复
热议问题