Reputation:
I have 4 files: f.h,f.cpp,g.h,g.cpp. both f.h and f.cpp include g.h, but f.cpp and g.cpp have a common helper function (Note f.h doesn't need it, but it needs definitions that are in g). At the moment I have the helper function as free standing in g.h (so that both g.cpp and f.cpp include it). However, this scares me because: 1.Whoever includes f.h can use it freely (meaning encapsulation) 2.If he has a function that has the same name as the free function it won't compile
I'm really hoping for a solution without code duplication (it's not a big helper functions, just a few lines. It's the principle :P).
Upvotes: 1
Views: 906
Reputation: 60051
You have a few options
What you describe (only a few .cpp
s need it and no one else should use it) sounds like what'd I'd call an "internal" function.
Make a new .h
file for this function and others like it called internal.h
or detail.h
or impl.h
or something sensical.
Put the function in f.h
(or even a new file like above) and use a namespace to section off code that should not be used by normal users.
namespace internal { // or "detail" or whatever
// function here
}
This is what many people and open source projects do.
If you really really don't want anything else to use this function, you can stick it as a private static member of a class and make friend only your classes.
class PrivateFunctions {
private:
// static your function
// friend your classes
};
I'd advise against this method though because it's uncommon, hard to change, and verbose
Upvotes: 1
Reputation: 1222
If you need more access control you can make it a friend
function.
Another option is to create a new file for the helper function and include it where needed. For only one function I wouldn't do that. Depends on you future plans.
Upvotes: 0
Reputation: 206577
Create g_f_private.h
. Add all the helper classes/functions/declarations in it that are used only by f.cpp
and g.cpp
.
#nclude
it in f.cpp
and g.cpp
.
Don't expose it to the users of f.h
and g.h
.
Upvotes: 2