Does target_link_libraries(... PRIVATE) deduplicate?

I have an embedded C application with static libraries, where both the application and lib1 use lib2. (lib2 is not part of lib1’s interface.)

If my CMakeLists.txt includes something like this:

add_executable(app app.c)
add_library(lib1 STATIC lib1.c)
add_library(lib2 STATIC lib2.c)

target_link_libraries(app PRIVATE lib1)
target_link_libraries(app PRIVATE lib2)

target_link_libraries(lib1 PRIVATE lib2)

Will the build process necessarily deduplicate all linked code? In other words, is there any chance of duplicate code in the final compiled executable, if e.g. both app and lib1 call the same function from lib2?

Since lib1 and lib2 are both static libraries, app should only end up with one copy of the code from lib2. It’s the linker’s job to resolve symbols needed by app’s object files. It will look through the lib1 and lib2 static libraries to resolve those symbols as needed. That’s a bit simplistic, but that’s the general idea.

1 Like