How to create a wrapper library without exposing the underlying library being used?

Viewed 85

Using Cmake I would like to know how to create a wrapper library and let the users link their application with this library only. Users don't need to specify the original library in their linker flags.

For instance, I create a wrapper library for libwebsockets, named libcustomws.

add_library(customws main.c)
target_link_libraries(customws websockets)

I would like user (with no libwebsockets installed) to be able to do:

add_executable(user_app user_app.c)
target_link_libraries(user_app customws pthread)
1 Answers

Wrapper libraries without any additional code from within your project can best be implemented with small INTERFACE library targets with the IMPORTED tag. Example for your scenario:

add_library(customws INTERFACE IMPORTED)

target_include_directories(customws
    INTERFACE
    /some/include/path)

target_link_libraries(customws
    INTERFACE
    websockets)

This way, targets that use this library can just

add_executable(user_app user_app.c)
target_link_libraries(user_app customws pthread)

and get the usage requirements from the target customws, in this case an include directory and a linked library (websockets) are propagated through customws. This can be a good thing, as it might encapsulate implementation details of the dependency (different flags for different platforms etc.).

If you like to automatically link to compiled code (that is part of your project), this can be easily done by adding a small intermediate OBJECT library, e.g.

add_libraray(customwsenhanced
    OBJECT
    someCode.c)

target_link_library(customwsenhanced
    PUBLIC
    customws)

Depending on whether someCode.c depends on the usage requirements of customws, the target_link_library for customwsenhanced could also use INTERFACE propagation. Now, a client application can go with

add_executable(user_app user_app.c)
target_link_libraries(user_app customwsenhanced pthread)

and will get both the compiled object code of someCode.c as well as flags etc. from customws.

Related