Conceptually, CMake considers each target (i.e., executable or library) as a separate assembly block. The generated assembly system will create an object file for each source file belonging to the target. By default, CMake does not avoid redundant compilation of source files, which are used for several purposes, even if the compilation options (compilation flags, preprocessor definitions ...) are exactly the same.
CMake 2.8.8 introduced a new function called OBJECT_LIBRARY to solve the problem of avoiding redundant compilations:
To create an object library, use add_library :
FILE(GLOB_RECURSE SAMPLE_SOURCE_FILES ${SAMPLE_SOURCE_PATH}/*.cpp) ADD_LIBRARY(sample_objects OBJECT EXCLUDE_FROM_ALL ${SAMPLE_SOURCE_FILES})
Other targets created by add_library or add_executable can refer to objects using an expression of the form $<TARGET_OBJECTS:objlib> :
ADD_EXECUTABLE(${SAMPLE_EXEC_NAME} $<TARGET_OBJECTS:sample_objects>) FILE(GLOB_RECURSE SAMPLE_TEST_SOURCE_FILES ${SAMPLE_TEST_SOURCE_PATH}/*.cpp) ADD_EXECUTABLE(${SAMPLE_TEST_EXEC_NAME} $<TARGET_OBJECTS:sample_objects> ${SAMPLE_TEST_SOURCE_FILES})
Compared to using a regular static library, to avoid redundant compilation, the object library has the advantage of not having to link it. In addition, it cannot be imported, exported, or installed.
source share