[CMake] Better handling of targets consisting of object files only

Vladimír Vondruš mosra at centrum.cz
Thu Apr 7 03:22:28 EDT 2016


Hello,

I'm using `OBJECT` libraries quite a lot in my projects and more often than not I run into a situation where a target consists only of `$<TARGET_OBJECTS>`. I know that CMake says the following about object libraries:

    "Some native build systems may not like targets that have only object files, so consider adding at least one real source file to any target that references $<TARGET_OBJECTS:objlib>."

One particular case of this is Xcode. But because my primary development happens with Ninja buildsystem, I don't experience the above issue at all until my CI starts testing with Xcode. Even then everything goes smoothly without any warning or error up to the final linking step, where the build just stops with something like this:

    clang: error: no such file or directory: '/path/to/the/project/build/Debug/liblib.a'

And then I spend *hours* looking where the problem is until I realize that it's those `OBJECT` libraries again.

That's where my question comes: Would it be possible to emit an error directly in the CMake configure/generate step for the affected buildsystems? In my experience it always led to linker error anyway, so why not inform the user as early as possible and hint what's the actual problem? (Or even better, because the solution is always to add a dummy C/C++ file to the target, it would be awesome if CMake could do just that implicitly. But I understand if that solution doesn't fit CMake's design.)

Minimal repro case, to make it easier:

    cmake_minimum_required(VERSION 3.5)

    project(XcodeObject)

    add_library(objects OBJECT lib.cpp)
    add_library(lib STATIC $<TARGET_OBJECTS:objects>)

    add_executable(exe main.cpp)
    target_link_libraries(exe lib)

The `lib.cpp` file is empty, the `main.cpp` is just `int main() {}`. Create build directory and experience the linker error with:

    cmake .. -G Xcode
    cmake --build .

Thank you for your input.

Regards
mosra


More information about the CMake mailing list