Search code examples
c++cmakecompilationheader-only

CMake target to just compile a source file


I am writing a header-only library using C++17. I would like to include it in a "dummy" source file:

#include "my/library.h"
// EOF

The purpose is to ensure the library properly includes all of its dependencies. I also want to run static analyzers on it and compile it with as many compiler checks enabled as is practical.

To create a normal executable target I need to add the main() function, otherwise the linking stage will fail. I guess I can also create a static library target, which should work correctly, although it will create an artifact I do not need.

Is there any other alternative?


Solution

  • CMake can create a simple Object library, which will only be a .o or .obj file:

    The OBJECT library type defines a non-archival collection of object files resulting from compiling the given source files.

    To do this, use the OBJECT keyword with the add_library() command:

    add_library(MyObj OBJECT ${CMAKE_CURRENT_SOURCE_DIR}/library.cpp)
    target_include_directories(MyObj PUBLIC ${CMAKE_CURRENT_SOURCE_DIR})
    

    You can later reference the object file(s) to be compiled into other libraries or executables:

    add_library(MyLibrary STATIC 
        $<TARGET_OBJECTS:MyObj> 
        MyOtherSource.cpp 
        HelpersFunctions.cpp
    )