I am trying to create a static library out of my source files. To illustrate the problem I am facing, let's consider the following snippet:
foo.h
:
void public_fn_exposed_to_client();
foo.cpp
:
#include "foo.h"
#include <iostream>
#define EXPORT __attribute__ ((visibility ("default")))
static void private_fn() {
std::cout << "Hello private world" << std::endl;
}
// Can't declare static as this can be used elsewhere in my lib.
// I tried to make this symbol hidden.
void internal_fn_used_inside_lib(){
std::cout << "Hello Internal Wolrd" << std::endl;
}
EXPORT
void public_fn_exposed_to_client()
{
std::cout << "Hello Outside World" << std::endl;
internal_fn_used_inside_lib();
}
main.cpp
(usually written by client):
#include "foo.h"
int main(int argc, char** argv)
{
// This is all good.
public_fn_exposed_to_client();
}
main2.cpp
(usually written by client):
#include "foo.h"
extern void internal_fn_used_inside_lib();
int main(int argc, char** argv)
{
// Ideally, This should not be allowed
internal_fn_used_inside_lib();
}
Compilation:
g++ -o foo.o foo.c -fvisibility=hidden
ar rcs libfoo.a foo.o
ranlib libfoo.a
g++ -o main1 main.cpp -L. -lfoo
g++ -o main2 main2.cpp -L. -lfoo
I want to achieve the case where main2 doesn't get compiled/linked. This is to discourage clients of my library to use the lower level functions that are not exposed as the API.
Particularly, how to deal with functions that cannot be declared as static?
Things that I have tried:
As mentioned in this, I tried to use objcopy with localize hidden flag, but nothing prevents the client from globalizing it again right?
Export maps - I don't know how to make them work with static archives. Rather I don't know if they are applicable at all.
Not possible. A static library can be thought of as a single file archive of all the unlinked object files. So what is visible were one to link an object file is visible from the static library as a whole.
The only way to "hide" things is by not providing the header file but nothing stops you user recreating those header files themself.