[CMake] Difference between PRIVATE and PUBLIC with target_link_libraries

Simon Richter Simon.Richter at hogyros.de
Wed Sep 18 05:56:16 EDT 2019


Hi,

On Tue, Sep 17, 2019 at 04:21:36PM -0700, Alan W. Irwin wrote:

> * It appears to me that if a CMake-based build system is configured
>   properly there is very little need for the PUBLIC option for TLL
>   because PRIVATE works well for shared libraries and the
>   PRIVATE-becomes-PUBLIC behaviour for static libraries you mentioned
>   above.  Can you confirm this statement is generally true both for
>   Unix and Windows?

The PUBLIC option is required if your library has inline functions that
directly call a dependent library.

On Windows, "shared" linking uses import stubs. Symbols used by dependent
libs were resolved when the dependent lib was linked, so they are not
available anymore. On ELF systems, whether symbols from indirectly linked
libs are available is implementation dependent -- older versions of glibc's
ld.so built a global namespace, so it might appear to work there, but that
is not guaranteed.

My expectation is that PRIVATE should work in all cases as long as your use
of the dependent library is indeed private -- i.e. doesn't affect the
binary interface of your library. Ideally, your headers wouldn't include
their headers, but in reality requirements are a bit more relaxed, so you
are fine as long as you don't have inline functions in headers that call
into the private dependency, and any compiler flags that affect data layout
in any shared types are consistent (e.g. if you use GLM, then
the definition of GLM_FORCE_PURE must be PUBLIC, because that affects
struct alignment requirements).

A good way to test is to do a fully static build with a compiler that
supports link time optimization and provides diagnostics for mismatches.
For example, we know we have a bug in the way KiCad uses GLM, because we
get -Wlto warnings[1] about that.

   Simon

[1] https://jenkins.simonrichter.eu/job/linux-kicad-head-lto/24/gcc/


More information about the CMake mailing list