Removing internal characters from the C static library

I am working on some inline code that comes as a static library. We would like to remove all internal characters from the library and save only API characters.

Here is an example of what we want to do: imagine that you have a file called internal.c and one called api.c that looks like this:

 /* internal.c */ int fibonacci(int n) { /* Compute the nth Fibonacci number and return it */ } /* api.c */ #include "internal.h" #include <stdio.h> void print_fibonacci(n) { printf("Fibonacci(%d): %d\n", n, fibonacci(n)); } 

The user should have access only to the print_fibonacci function, and all internal characters, such as the fibonacci function, must be allowed before sending. This means that the user should be able to define his own function called fibonacci , without worrying about conflicts with the library.

We have already tried intercom using ld --relocatable , but we cannot apparently remove characters after using objcopy. Is this even possible?

Thanks for the help!

Edit: A custom fibonacci function should not replace a library-specific function, it should just be able to coexist. I am mainly looking for a solution to resolving name conflicts.

+7
c linker binaryfiles static-libraries
source share
1 answer

Static libraries are essentially a bunch of object files. All object files in the static library are processed as if they were provided individually by the linker. As a rule, it is impossible to make the linker process some characters as internal; the linker simply does not have enough information for this.

Here are some strategies to solve these problems:

  • Create a separate namespace for non-public functions in your library. For example, your fibonacci function can be placed in the libfoo_internal_fibonacci internal namespace. If you desparate, you can use macros in your internal header files as follows:

     #define fibonacci INTERNAL_PREFIX ## fibonacci 

    This will allow you to arbitrarily change the prefix at compile time. I suggest not doing this as this makes debugging more difficult. If you handle longer internal names, this would be a good strategy.

  • Make all internal functions static and combine translation units so that each internal function is used by only one translation unit. This may solve your problem, but it leads to the fact that the resulting programs are larger: most linkers can either take the whole object or not accept it at all. There may be a lot of dead code in the program if the linker has to include huge object files if you want to use only one function.

  • Turn your library into a shared library and use mapfiles or some other mechanism to indicate which characters should be exported. In my opinion, this is the best option, but it is not fully portable and maybe you really want your library to remain static.

+3
source share

All Articles