How does target_link_libraries with the PUBLIC flag actually work?

I’m curious how the use of the PUBLIC flag in target_link_libraries actually works. As an example, say I create a library libA.so which depends on libB.so. Some elements of libB.so are in the public interface of A, so I configure it with cmake thusly:

target_link_library(A PUBLIC B)

Now, someone creates a library libUserLibrary.so and wants to use my library A. They link against it, and thereby libUserLibrary.so links against both libA.so and libB.so.

How is this actually done with the C++ linker?

Thanks!

CMake creates a link line for libUserLibrary.so that has both libA.so and libB.so on it ( g++ -fPIC -shared ... -o libUserLibrary.so <path/>libA.so <path/>libB.so ... )

How does the linker become aware that libB is “public”, though?

Linker has no idea :wink:

CMake tracks those things and in the end generates the linker command. If you used PUBLIC or INTERFACE, the linker command will look like @robert.maynard showed. If you used PRIVATE, it’ll be g++ -fPIC -shared ... -o libUserLibrary.so <path/>libA.so ...

1 Like