简体   繁体   中英

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?

Most compilers allow you to override the default extension for input types. If you just pass my/library.h as the input file to the compiler, it can compile that into a library.o or library.obj .

Note that short of compiling an executable, you can't be sure that your library.h is complete. In particular, C++ requires that non- inline static const class members are defined exactly once per program if they're odr-used. So if you forget inline in your library.h , you might not notice this in your simple test. And even if you'd add an empty main() , that still wouldn't odr-use those members.

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
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM