Search code examples
c++gccg++c++14

Strip everything except API from C++ static lib?


I have a static library that I need to remove unwanted symbols from. There are only two external facing public API functions.

I'm struggling to strip the archive such that only the external API is exposed in the library.If I use something like:

objcopy --keep-global-symbol=some-mangled-cpp-symbol-name liblibrary.a liblibrary.a && ranlib liblibrary.a

...then I get a linker error when I attempt to link against the new archive:

$ g++ -I $(pwd)/install/include -L$(pwd)/build -o main test_app.cpp -llibrary.a
/usr/bin/ld: error in ...liblibary.a(filename.cpp.o)(.eh_frame); no .eh_frame_hdr table will be created

Followed by a segfault when the code is run.

Any fixes or alternative techniques for getting rid of all the extraneous symbols?


Solution

  • In a static library, there is no such thing as "external facing public API functions". Any function that was not declared static is equally part of the library, as far as the compiler and linker are concerned. Any code could declare those functions and link with your library and thereby access them.

    C++ as a language does not deal in "libraries"; it deals in "translation units" (.cpp files). So its scoping is limited to either everyone or just this TU.

    However, C++20 has a tool way to declare functions that are, for all intents and purposes, internal to a library: modules. A name that is module scoped but not exported cannot be declared and accessed by code outside of that module. As such, it would be theoretically possible to strip out any non-exported, module scoped code that isn't used by the module itself.