Hosdgfag2
Hosdgfag2

Reputation: 151

Ok to not include some non-member functions in header?

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

Answers (4)

vishal
vishal

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

BigTailWolf
BigTailWolf

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:

header.h

class Foo
{
};

void f()
{
}

b.cpp

# include "header.h"

a.cpp

# include "header.h"

int main()
{
}

Compiling OK but link error:

[~]$ 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:

header.h

class Foo
{
};

void f();

b.cpp

#include "header.h"

void f()
{
}

a.cpp

#include "header.h"

int main()
{
}

Then it will be fine

[~]$ g++ -c a.cpp
[~]$ g++ -c b.cpp
[~]$ g++ -o run a.o b.o
[~]$

Also, the static works for that as the posts above said.

Upvotes: 1

Anon Mail
Anon Mail

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

Thomas Matthews
Thomas Matthews

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

Related Questions