Search code examples
c++linkervisibility

How to correctly link a C++ library that has different behaviors depending on its compilation?


I have a library called Print and the function println, which mimics printf. If compiled with the directive USE_DEBUG_PRINT, println actually prints something. If compiled without this define, it prints nothing.

Then I want to use this library inside another library, let's call it A. A uses Print with this directive defined. Another library, 'B', uses 'Print' without this directive, so println has different behaviors for them.

However, when compiling into an application, depending on the link order, B will use println from A, or the opposite. This happens because the println symbol is defined for both of the libs, so the linker just picks the first.

How can I, instead, make Print "private" for these libs? I don't want anyone using A or B to have access to the println function regardless, so they can just be "merged" together, keeping println out of the 1.txt files, being used only in their implementations.

I'm using Clang and CMake to generate both libs and the app. Print is an object library, while the other ones are static.


Solution

  • I managed to solve this by doing the following:

    • Print is now an interface, containing just a header file.
    • println is marked as static.

    This way, it can be included in any .cpp file, and be compiled with the options it defined without affecting other compilations.