C++ static local function vs global function

大城市里の小女人 提交于 2020-01-11 17:18:29

问题


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)
{
   return i * i;
} 

vs

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

回答1:


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

You can use these functions to provide shared implementation logic to other functions within the same file. Various helper functions specific to a file are good candidates to be declared file-static.

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

They are invisible to the linker, allowing other compilation units to define functions with the same signature. Using namespaces alleviates this problem to a large degree, but file-static functions predate namespaces, because they are a feature inherited from the C programming language.




回答2:


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.




回答3:


Static functions are visible on the file where they were defined only. You can't refer to them outside of that particular file.

Read more here




回答4:


In a word, linkage. static functions have internal linkage, that is, they aren't visible outside of their translation unit.



来源:https://stackoverflow.com/questions/14742664/c-static-local-function-vs-global-function

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!