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 which depends on Some elements of 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 and wants to use my library A. They link against it, and thereby links against both and

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


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

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 <path/> ...

1 Like