Skip to content

Instantly share code, notes, and snippets.

@jthemphill
Created October 16, 2023 04:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jthemphill/f212b087482c701fa924261f741d09a7 to your computer and use it in GitHub Desktop.
Save jthemphill/f212b087482c701fa924261f741d09a7 to your computer and use it in GitHub Desktop.
cmake_minimum_required(VERSION 3.12)
# A reproduction of the example given in
# https://cmake.org/cmake/help/latest/command/target_link_libraries.html#linking-object-libraries
project(CMakeTest)
# Object Libraries may be used as the <target> (first) argument of target_link_libraries to specify dependencies of their sources on other libraries. For example, the code
add_library(A SHARED a.c)
target_compile_definitions(A PUBLIC A)
# compiles obj.c with -DA -DOBJ and establishes usage requirements for obj that propagate to its dependents.
# Normal libraries and executables may link to Object Libraries to get their objects and usage requirements. Continuing the above example, the code
add_library(obj OBJECT obj.c)
target_compile_definitions(obj PUBLIC OBJ)
target_link_libraries(obj PUBLIC A)
# compiles b.c with -DA -DOBJ, creates shared library B with object files from b.c and obj.c, and links B to A. Furthermore, the code
add_library(B SHARED b.c)
target_link_libraries(B PUBLIC obj)
# compiles b.c with -DA -DOBJ, creates shared library B with object files from b.c and obj.c, and links B to A. Furthermore, the code
add_executable(main main.c)
target_link_libraries(main B)
# compiles main.c with -DA -DOBJ and links executable main to B and A. The object library's usage requirements are propagated transitively through B, but its object files are not.
# Object Libraries may "link" to other object libraries to get usage requirements, but since they do not have a link step nothing is done with their object files. Continuing from the above example, the code:
add_library(obj2.o OBJECT obj2.c)
target_link_libraries(obj2.o PUBLIC obj)
add_library(obj2 INTERFACE)
target_link_libraries(obj2 INTERFACE obj2.o)
add_executable(main2 main2.c)
target_link_libraries(main2 obj2)
# compiles obj2.c with -DA -DOBJ, creates executable main2 with object files from main2.c and obj2.c, and links main2 to A.
# In other words, when Object Libraries appear in a target's INTERFACE_LINK_LIBRARIES property they will be treated as Interface Libraries, but when they appear in a target's LINK_LIBRARIES property their object files will be included in the link too.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment