Accessing a function through inclusion vs declaring static - c++

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?

That is a pretty evil header file you're showing.
Never put using namespace std; into a header file. This forces anyone including the header to have all of std in the global namespace.
Use some form of include guards.
static makes the function invisible outside the .cpp where it's included. This means that every .cpp which includes the header will have its own copy of the function. static (non-member) functions should only be used if you specifically need this behaviour.
If you don't use static, you should either move the definition from the header into a source file (if you want it defined once), or declare the function inline (its code will then be inlined on every call site, if possible). If you do neither of these, you'll get multiple definition errors if you include the header in more than one source file.

The first header file defines a function called ret with 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 ret with 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:
function with internal linkage (as in your second header, or in C++11 by putting it in a nameless namespace).
inline function with external linkage (replace static with inline). The meaning of inline is that although there is only one copy of the function in the program, every TU that uses the function contains its definition.
declare the function in the header, and define in it exactly one .cpp file (for example ret.cpp).
In C++03 there was a fourth way:
function with external linkage in a nameless namespace
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 (static or inline) differ in their behaviour if:
the function contains static local variables,
you compare function pointers to ret taken in different TUs,
you examine your executable size or symbol table,
the definition of the function is different in different TUs (perhaps due to different #defines), which is forbidden if the function has external linkage but not if internal.
Otherwise they're much the same.
According to the standard, inline is 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 a static but non-inline function if they assess it to be a good candidate for inlining, and they will happily avoid inlining an inline function if they assess it to be a bad candidate for inlining.

Use header guards.
Don't use "using namespace" in header files. (Actually, don't use "using" in header files. Use identifiers fully qualified.)
And use a header for declaring functions, not for defining them. You will want the code for ret() to be present in the resulting executable only once. You achieve this by putting the definition (code) of ret() in a .cpp file. One .cpp file, not multiple ones (by including the definition).
The header file lists the declaration of the function ret() so that other code "knows" that the function exists, which parameter it takes, and what it returns.

If you define c++ methods as static in the header file, each translation unit ( each .cpp file which includes that header file ) will have different versions of those static methods - they will not have the same address space.
Hence the size of your program will increase unnecessarily.
Also, just for clarity:
Defining a method as static only in the .cpp file means that the method has static linkage and is only accessible from other methods within the same .cpp file.

Related

C++ redefinition link error when not using "inline" or "static" keywords with classless functions

So I realize that when including a ".h" file, the compiler essentially copies the contents of that file to the point it was included. So obviously if I had "Utils.h" included in many files, if utils.h holds a functions implementation, it would cause the redefinition error.
I also realize using the inline keyword fixes this problem by essentially eliminating the function and in-lining it at its usage sites.
Now my question is, when the static keyword is used in the header file, it also seems to fix the problem, but I'm not sure I quite understand why/how it fixes the problem...? It's my understanding that static in a cpp file would essentially make it only available in that compilation unit.
To make sure we're all on the same page here is a snippet of the code in question:
//Utils.h (included in many places)
namespace utils {
void someUtil() {
//do work
}
}
where the above would throw the error, but with static and/or inline keyword, there would be no issue.
So I'm wanting to know what static is doing in this case, and should I use that as well as inline if its a small function body or...?
static, tells the compiler to generate the function in every translation unit where it is defined, and just not share it. So you end up with an arbitrary number of technically separate functions existing in the resulting executable if you use in many translation units and if you check the address of the function in different TUs you will have different results.
inline function on the other hand:
There may be more than one definition of an inline function or
variable (since C++17) in the program as long as each definition
appears in a different translation unit and (for non-static inline
functions and variables (since C++17)) all definitions are identical.
For example, an inline function or an inline variable (since C++17)
may be defined in a header file that is #include'd in multiple source
files.
So The compiler will then either inline calls to the function, or merge together the function definitions from different TU's (so that the resulting function exists once in the executable).
so in your case inline is what you need.

Anonymous namespace to include a function in two cpp files

I have a function which should be included in two different translation units (i.e. cpp files) from a common header.
I might use an anonymous namespace to have this function included in both TUs without conflicts but I'm wondering what would be the best way to accomplish this (static? I don't think global could work, multiple definitions)
If you want it to be the same function in every TU, use inline. That's exactly what inline is for: shared functions defined in headers.
In the admittedly-unlikely event that you want it to be a different function in every TU, use either an unnamed namespace or static. I don't think the standard gives an official view which one is preferred in C++, but you kind of get the impression it's the unnamed namespace.
Which one you want depends on why you're putting a function definition in a header file in the first place, and how you intend the header to be used.
You need to learn the difference between declaration of function and it's definition. Except of template and inline functions only function declaration should be in a header file, function definition should be in translation unit.
void foobar( int ); // this is function declaration, now you can call this function
// you can put it on your sources as many times as you want
void foobar( int param ) { // this is function definition, it should appear only once
...
}
If you want that the compiler would consider this function as a different function in each CU you can include its definition in an unnamed namespace. According to the C++ 2011 Standard entities declared in unnamed namespaces have internal linkage.

static inline free function [duplicate]

I know what it means when static function is declared in source file. I am reading some code, found that static function in header files could be invoke in other files.
Is the function defined in the header file? So that the actual code is given directly in the function, like this:
static int addTwo(int x)
{
return x + 2;
}
Then that's just a way of providing a useful function to many different C files. Each C file that includes the header will get its own definition that it can call. This of course wastes memory, and is (in my opinion) a quite ugly thing to be doing, since having executable code in a header is generally not a good idea.
Remember that #include:ing a header basically just pastes the contents of the header (and any other headers included by it) into the C file as seen by the compiler. The compiler never knows that the one particular function definition came from a header file.
UPDATE: In many cases, it's actually a good idea to do something like the above, and I realize my answer sounds very black-and-white about this which is kind of oversimplifying things a bit. For instance, code that models (or just uses) intrinsic functions can be expressed like the above, and with an explicit inline keyword even:
static inline int addTwo(int *x)
{
__add_two_superquickly(x);
}
Here, the __add_two_superquickly() function is a fictional intrinsic, and since we want the entire function to basically compile down to a single instruction, we really want it to be inlined. Still, the above is cleaner than using a macro.
The advantage over just using the intrinsic directly is of course that wrapping it in another layer of abstraction makes it possible to build the code on compilers lacking that particular intrinsic, by providing an alternate implementation and picking the right one depending on which compiler is being used.
It will effectively create a separate static function with the same name inside every cpp file it is included into. The same applies to global variables.
As others are saying, it has exactly the same meaning as a static function in the .c file itself. This is because there is no semantic difference between .c and .h files; there is only the compilation unit made up of the file actually passed to the compiler (usually named .c) with the contents of any and all files named in #include lines (usually named .h) inserted into the stream as they are seen by the preprocessor.
The convention that the C source is in a file named .c and public declarations are in files named .h is only a convention. But it is generally a good one. Under that convention, the only things that should appear in .h files are declarations so that you generally avoid having the same symbol defined more than once in a single program.
In this particular case, the static keyword makes the symbol be private to the module, so there isn't a multiple-definition conflict waiting to cause trouble. So in that one sense, it is safe to do. But in the absence of a guarantee that the function would be inlined, you take the risk that the function would be instantiated in every module that happened to #include that header file which at best is a waste of memory in the code segment.
I am not certain of what use cases would justify doing this at all in a generally available public header.
If the .h file is generated code and only included in a single .c file, then I would personally name the file something other than .h to emphasize that it isn't actually a public header at all. For example, a utility that converts a binary file into an initialized variable definition might write a file that is intended to be used via #include and could very well contain a static declaration of the variable, and possibly even static definitions of accessor or other related utility functions.
If you define the function in a header file (not simply declare it), a copy of the function will be generated in each translation unit (basically in each cpp file which includes this header).
This may increase the size of your executable, but this may be negligible if the function is small. The advantage is that the most compilers may inline the function, which may increase the code performance.
But there may be a big difference in doing this which wasn't mentioned in any answer. If your function uses a static local variable such as:
static int counter()
{
static int ctr = 0;
return ctr++;
}
Rather than:
//header
int counter();
//source
int counter()
{
static int ctr = 0;
return ctr++;
}
Then each source file including this header will have its own counter. If the function is declared inside the header, and defined in a source file, then the counter will be shared across your whole program.
So saying that the only difference will be performance and code size is wrong.
There is not semantic difference in defining in source file or header file, basically both means the same in plain C when using static keyword that, you are limiting the scope.
However, there is a problem in writing this in header file, this is because every time you include the header in a source file you'll have a copy of the function with same implementation which is much similar to have a normal function defined in header file. By adding the definition in header you are not achieving the what the static function is meant for.
Therefore, I suggest you should have your implementation only in your source file and not in header.
It is usefull in some "header-only" libraries with small inline functions. In a such case you always want to make a copy of the function so this is not a bad pattern. However, this gives you an easy way to insert separate interface and implementation parts in the single header file:
// header.h
// interface part (for user?!)
static inline float av(float a, float b);
// implementation part (for developer)
static inline float av(float a, float b)
{
return (a+b)/2.f;
}
Apple vector math library in GLK framework uses such constuction (e.g. GLKMatrix4.h).

What's the difference between inline member function and normal member function?

Is there any difference between inline member function (function body inline) and other normal member function (function body in a separate .cpp file)?
for example,
class A
{
void member(){}
};
and
// Header file (.hpp)
class B
{
void member();
};
// Implementation file (.cpp)
void B::member(){}
There is absolutely no difference.
The only difference between the two is that the member inside the class is implicitly tagged as inline. But this has no real meaning.
See: inline and good practices
The documentation says that the inline tag is a hint to the compiler (by the developer) that a method should be inlined. All modern compilers ignore this hint and use there own internal heuristic to determine when a method should be inlined (As humans are notoriously bad and making this decision).
The other use of inline is that it tells the linker that it may expect to see multiple definitions of a method. When the function definition is in the header file each compilation unit that gets the header file will have a definition of the function (assuming it is not inlined). Normally this would cause the linker to generate errors. With the inline tag the compiler understands why there are multiple definitions and will remove all but one from the application.
Note on inlining the processes: A method does not need to be in the header file to inlined. Modern compilers have a processes a full application optimization where all functions can be considered for inlining even if they have been compiled in different compilation units. Since the inline flag is generally ignored it make no difference if you put the method in the header or the source file.
Ignore the word inline here and compiler hints because it is not relevant.
The big practical difference in A and B is when they are used in different libraries.
With the case of A you can #include the header and are not required to link against anything. So you can use this class from different applications / libraries without any special linkage.
With the case of B, you need B.cpp and this should be compiled only into one library / application. Any other library or application that needs to use this class will need to link against the one that contains the actual body of the code.
With some setups / implementations you will need to specifically mark the class as "exported" or "imported" between libraries (for example with Windows you can use dllimport / dllexport and with GNU you can use attribute(visibility="default") )
The first one is implicitly inline, i.e. suggesting the compiler to expand it at the call site.
Other than the inline thing, there's a difference in that you could put more definitions in between the definition of class B, and the definition of the function.
For example, B.cpp might include header files that B.hpp doesn't, which can make a significant difference to the build process for large projects.
But even without a separate translation unit, you can occasionally have a circular dependency that's resolved by separating the definitions. For example the function might take a parameter of a type that's forward-declared before B is defined, then defined by the time the function is defined. If that type uses the definition of B in its own definition, it can't just be be defined before B.

C/C++: Static function in header file, what does it mean?

I know what it means when static function is declared in source file. I am reading some code, found that static function in header files could be invoke in other files.
Is the function defined in the header file? So that the actual code is given directly in the function, like this:
static int addTwo(int x)
{
return x + 2;
}
Then that's just a way of providing a useful function to many different C files. Each C file that includes the header will get its own definition that it can call. This of course wastes memory, and is (in my opinion) a quite ugly thing to be doing, since having executable code in a header is generally not a good idea.
Remember that #include:ing a header basically just pastes the contents of the header (and any other headers included by it) into the C file as seen by the compiler. The compiler never knows that the one particular function definition came from a header file.
UPDATE: In many cases, it's actually a good idea to do something like the above, and I realize my answer sounds very black-and-white about this which is kind of oversimplifying things a bit. For instance, code that models (or just uses) intrinsic functions can be expressed like the above, and with an explicit inline keyword even:
static inline int addTwo(int *x)
{
__add_two_superquickly(x);
}
Here, the __add_two_superquickly() function is a fictional intrinsic, and since we want the entire function to basically compile down to a single instruction, we really want it to be inlined. Still, the above is cleaner than using a macro.
The advantage over just using the intrinsic directly is of course that wrapping it in another layer of abstraction makes it possible to build the code on compilers lacking that particular intrinsic, by providing an alternate implementation and picking the right one depending on which compiler is being used.
It will effectively create a separate static function with the same name inside every cpp file it is included into. The same applies to global variables.
As others are saying, it has exactly the same meaning as a static function in the .c file itself. This is because there is no semantic difference between .c and .h files; there is only the compilation unit made up of the file actually passed to the compiler (usually named .c) with the contents of any and all files named in #include lines (usually named .h) inserted into the stream as they are seen by the preprocessor.
The convention that the C source is in a file named .c and public declarations are in files named .h is only a convention. But it is generally a good one. Under that convention, the only things that should appear in .h files are declarations so that you generally avoid having the same symbol defined more than once in a single program.
In this particular case, the static keyword makes the symbol be private to the module, so there isn't a multiple-definition conflict waiting to cause trouble. So in that one sense, it is safe to do. But in the absence of a guarantee that the function would be inlined, you take the risk that the function would be instantiated in every module that happened to #include that header file which at best is a waste of memory in the code segment.
I am not certain of what use cases would justify doing this at all in a generally available public header.
If the .h file is generated code and only included in a single .c file, then I would personally name the file something other than .h to emphasize that it isn't actually a public header at all. For example, a utility that converts a binary file into an initialized variable definition might write a file that is intended to be used via #include and could very well contain a static declaration of the variable, and possibly even static definitions of accessor or other related utility functions.
If you define the function in a header file (not simply declare it), a copy of the function will be generated in each translation unit (basically in each cpp file which includes this header).
This may increase the size of your executable, but this may be negligible if the function is small. The advantage is that the most compilers may inline the function, which may increase the code performance.
But there may be a big difference in doing this which wasn't mentioned in any answer. If your function uses a static local variable such as:
static int counter()
{
static int ctr = 0;
return ctr++;
}
Rather than:
//header
int counter();
//source
int counter()
{
static int ctr = 0;
return ctr++;
}
Then each source file including this header will have its own counter. If the function is declared inside the header, and defined in a source file, then the counter will be shared across your whole program.
So saying that the only difference will be performance and code size is wrong.
There is not semantic difference in defining in source file or header file, basically both means the same in plain C when using static keyword that, you are limiting the scope.
However, there is a problem in writing this in header file, this is because every time you include the header in a source file you'll have a copy of the function with same implementation which is much similar to have a normal function defined in header file. By adding the definition in header you are not achieving the what the static function is meant for.
Therefore, I suggest you should have your implementation only in your source file and not in header.
It is usefull in some "header-only" libraries with small inline functions. In a such case you always want to make a copy of the function so this is not a bad pattern. However, this gives you an easy way to insert separate interface and implementation parts in the single header file:
// header.h
// interface part (for user?!)
static inline float av(float a, float b);
// implementation part (for developer)
static inline float av(float a, float b)
{
return (a+b)/2.f;
}
Apple vector math library in GLK framework uses such constuction (e.g. GLKMatrix4.h).