[CMake] Difference between PRIVATE and PUBLIC with target_link_libraries

iosif neitzke iosif.neitzke+cmake at gmail.com
Wed May 11 06:33:18 EDT 2016


>> I *think* that these public/private rules behave a bit differently
>> for static libraries than they do for shared ones.

They do.  Assuming main calls a() and b() defined in A_lib and B_lib
respectively, for:
add_library(A_lib STATIC a.c)
add_library(B_lib STATIC b.c)
target_link_libraries(A_lib PRIVATE B_lib)
add_executable(main main.c)
target_link_libraries(main A_lib)

The PRIVATE in "target_link_libraries(A_lib PRIVATE B_lib)" is
useless.  It is the same as writing "target_link_libraries(A_lib
PUBLIC B_lib)", only more confusing to the reader. Static libraries
always link to their dependencies publically.

https://cmake.org/cmake/help/v3.5/command/target_link_libraries.html#libraries-for-a-target-and-or-its-dependents

However, if you change A_lib to be a shared library with
"add_library(A_lib SHARED a.c)" and left the rest of the code the
same, you would now get link errors for main not able to find b(),
because A_lib now does not pass on its dependency on B, it hides it
from main.   Change the last line to "target_link_libraries(main A_lib
B_lib)" and main builds again.


More information about the CMake mailing list