C ++ Function Prototypes

I just started to learn C ++. Can someone explain the difference between the following C ++ function prototypes?

void f(int n); extern void f(int n); static void f(int n); 
+4
source share
5 answers

The options void and extern void are the same. They indicate that the function has an external connection (i.e., the function definition may come from some other C or C ++ file). Static indicates that the function has an internal relationship and will exist only in the current C ++ file.

You almost never see these qualifiers applied to functions, because 99.9% of the time you want extern to be default.

You can see static or extern storage specifiers for global variables, although this is often done to reduce name conflicts with other files in the same project. This is a respite from C; if you use C ++, this should be done with an anonymous namespace instead of static .

+11
source

This is more of a question in C than C ++, 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 it is a .cpp file, the function will be visible only to this file. If it is in the .h file, each .cpp file containing this header will create its own copy of this function, available only for this implementation file.

+4
source

The first two are one and the same. The third gives f internal connection, which means that another source file can use the name f as something else.

Using static , as in this third example, should not be used. Use an anonymous namespace instead:

 namespace { // anonymous void f(int n); } 
+3
source

Both answers so far have not recommended using static functions. What for? What is he doing

namespace {
void f (int n); }

superior to

static void f (int n);

? It is not easier, it is not easier to understand ...

0
source

Anonymous namespace is a more universal and cleaner solution, it can contain functions, variables, classes. And static too overloaded, in some contexts an internal relationship is implied, in others it is a static lifetime.
However, there is one drawback to the anonymous namespace. Due to external communication, the exported section of your object / library files will inflate with all these long names <unique namespace name>::<function> , which would not exist if they were static.

0
source

All Articles