C++ function prototypes
I have just started learning C++. Can some explain the difference between the following C+开发者_JAVA百科+ function prototypes?
void f(int n);
extern void f(int n);
static void f(int n);
The void and extern void versions are the same. They indicate that the function has external linkage (i.e. the definition of the function may be expected to come from some other C or C++ file). Static indicates that the function has internal linkage, and will exist only in the current C++ file.
You almost never see these specifiers applied to functions because 99.9% of the time you want the default extern
behavior.
You may see the static
or extern
storage specifiers on global variables though, which is often done to reduce name conflicts with other files in the same project. This is a holdover from C; if you're using C++ this kind of thing should be done with an anonymous namespace instead of static
.
This is more of a C-language question than a C++ one, but:
void f(int n);
Declares a function f that takes a single integer parameter.
extern void f(int n);
Declares a function f that takes a single integer parameter but exists in some other file. The compiler will trust that you have implemented the function somewhere. If the linker cannot find it, you will get a linker error.
static void f(int n);
Declares a function f that takes a single integer parameter. The static keyword makes this interesting. If this is in a .cpp file, the function will only be visible to that file. If it is in a .h file, every .cpp file that includes that header will create its own copy of that function that is only accessible to that implementation file.
The first two are the same thing. The third one gives f
internal linkage, meaning that a different source file may use the name f
to be something different.
The use of static
as in that third example should not be used. Instead use an anonymous namespace:
namespace { // anonymous
void f(int n);
}
Both answers so far have deprecated the use of static functions. Why? What makes
namespace {
void f(int n);
}
superior to
static void f(int n);
? It's not simpler, it's not easier to understand...
Anonymous namespace is a more universal and cleaner solution, you can have functions, variables, classes in it. And static
is way too overloaded, in some contexts meaning internal linkage, in others static lifetime.
There is one disadvantage of anonymous namespace though. Because of external linkage, the exported section of your object/library files will swell with all those long <unique namespace name>::<function>
names which wouldn't be there is they were static.
精彩评论