Search code examples
cposixldstatic-linkingobject-files

Hiding non-API symbols in library


Suppose I have a library foo which consists of the modules foo and util and has the following source tree:

foo/
    foo.c
    foo.h
    util.c
    util.h

The public API of the library is defined in foo.h and all global identifiers are properly prefixed with foo_ or util_. The module util is only used by foo. To prevent name clashes with other modules named util I want to create a (static) library in which only identifiers from module foo are visible. How can I do this?

Edit: I have searched the internet quite extensively but surprisingly this seems to be one of those unsolved problems in computer science.


Solution

  • Before each variable and function declaration in util.h, define a macro constant which renames the declared identifier by adding the library prefix foo_, for instance

    #define util_x foo_util_x
    extern int util_x;   
    
    #define util_f foo_util_f
    void util_f(void);
    
    ...
    

    With these definitions in place, no other parts of the code need to be changed, and all global symbols in the object file util.o will be prefixed with foo_. This means that name collisions are less likely to occur.