I have a header file I want to include in another cpp file. I want to know what is the difference if I write the header file like this,
#include <iostream>
#include <string>
using namespace std;
string ret()
{
return "called";
}
===================================
#include <iostream>
#include <string>
using namespace std;
static string ret()
{
return "called";
}
I can access the ret() function anyway!! So, what’s the use of the static?
The first header file defines a function called
retwith external linkage in every translation unit that includes it. This is incorrect if more than one such TU is linked in the same program.The second header file defines a function called
retwith internal linkage in every translation unit that includes it. This means that each TU has its own private copy of the function (with a different address) no matter how many are linked together.There are three correct ways to share code using a header file:
staticwithinline). The meaning ofinlineis that although there is only one copy of the function in the program, every TU that uses the function contains its definition.In C++03 there was a fourth way:
I believe this is still available in C++11, but in C++11 functions in nameless namespaces have internal linkage by default. I’m not aware of any use in C++11 for making a function in a nameless namespace have external linkage. So as far as functions are concerned, nameless namespaces are a nice way of giving the function internal linkage.
Which one you use depends on your needs. The third option means that you can change the definition of the function without re-compiling the calling code, although you’d still need to re-link the executable unless the function is in a dll.
The first two (
staticorinline) differ in their behaviour if:staticlocal variables,rettaken in different TUs,Otherwise they’re much the same.
According to the standard,
inlineis also a hint that the compiler should optimize calls to that function for fast execution (which in practice means, inline the code at the call site). Most compilers ignore this hint most of the time. They will happily inline astaticbut non-inlinefunction if they assess it to be a good candidate for inlining, and they will happily avoid inlining aninlinefunction if they assess it to be a bad candidate for inlining.