Reputation: 151
If you want some non-member functions to be possible to be called only by functions in the same translation unit, is ok to not define them in the header?
Upvotes: 2
Views: 801
Reputation: 2391
You can just put functions in their own namespace so that it doesn't interfere with rest code. A common practice is to make the namespace an inner namespace of your main library namespace and to call it details or something similar.
Of course, if you need to function to be available through ADL(argument dependent lookup) then it has to live in the namespace enclosing the classes for which the ADL is supposed to match. There's no way around this.
Upvotes: 0
Reputation: 1028
It's OK to declare them in header file. But if you define them in the header and the header was included by more than one compiling unit, it will cause a link error of confliction.
See this example:
class Foo
{
};
void f()
{
}
# include "header.h"
# include "header.h"
int main()
{
}
[~]$ g++ -c a.cpp
[~]$ g++ -c b.cpp
[~]$ g++ -o run a.o b.o
b.o: In function `f()':
b.cpp:(.text+0x0): multiple definition of `f()'
a.o:a.cpp:(.text+0x0): first defined here
collect2: error: ld returned 1 exit status
[~]$
Alternately, if you separate the declaration and definition like this:
class Foo
{
};
void f();
#include "header.h"
void f()
{
}
#include "header.h"
int main()
{
}
[~]$ g++ -c a.cpp
[~]$ g++ -c b.cpp
[~]$ g++ -o run a.o b.o
[~]$
Upvotes: 1
Reputation: 4770
This is common. Keeps clutter out of the header file. Normally, you would put them in an anonymous namespace in the .cpp file.
You can accomplish this without an anonymous namespace by using the static keyword.
Upvotes: 4
Reputation: 57739
Yes, non-member functions can be placed inside the translation unit.
Declare and define them as static
so they are private within the translation unit.
Upvotes: 1