I have a class Foo
defined in a header foo.hpp
.
class Foo{
... some methods and properties ...
};
Furthermore, I need a function bar()
which shall have the following properties:
- The function
bar()
shall be defined in the filefoo.cpp
and its symbols shall not be exported, I want to use internal linkage becausebar()
is only used infoo.cpp
. - The function
bar()
shall have access to the private elements of the functionFoo
. - The function
bar()
cannot be a member function because I want to pass its address to another function which uses it as a callback.
Is the above possible in C++?
I tried the following: Since the linkage shall be internal, I need to use the static
keyword for bar()
(see for example here). Furthermore, bar()
needs to be declared as a friend
of Foo
in foo.hpp
because it shall have access to its private members. Following this explaination, I need to declare bar()
prior to Foo
as static. So I adapted this in foo.hpp
static void bar();
class Foo{
... some methods and properties ...
friend void bar();
};
Then foo.cpp
would contain the code
static void bar(){
... definition of bar()
}
However, this has the following disadvantages:
In other compilation units that do not involve
foo.cpp
I get a warning saying something likedeclared ‘static’ but never defined
.The declaration of
bar()
is visible to any code that is includingfoo.hpp
. I don't want that, as one could use this to access private members ofFoo
by redefiningbar()
in other compilation units.
So this does not work. How would you solve this problem?
NOTE: Of course bar()
actually has some parameters that are used to access a specific instance of Foo
. I omitted them here.