Search code examples
c++cmakegcov

CMake- what is the difference between 'target_link_options(.. -lgcov)' and 'target_link_libraries(...gcov)'?


I'm trying to build a library with code coverage enabled like so:

    add_library(my_library my_lib.cpp)
    target_compile_options(my_library PRIVATE --coverage)
    target_link_options(my_library PRIVATE -lgcov)

and then later I have some tests for the library:

    add_executable(my_test my_test.cpp)
    target_link_libraries(my_test my_library)

However I get link errors when building the tests-

libmy_library.a(my_lib.cpp.o): In function `_GLOBAL__sub_I_00100_0__ZN7myClass10returnTrueEv':
my_lib.cpp:(.text+0x2f): undefined reference to `__gcov_init'
libmy_library.a(my_lib.cpp.o): In function `_GLOBAL__sub_D_00100_1__ZN7myClass10returnTrueEv':
my_lib.cpp:(.text+0x3a): undefined reference to `__gcov_exit'
libmy_library.a(my_lib.cpp.o):(.data.rel+0x20): undefined reference to `__gcov_merge_add'

If instead of using target_link_options I use target_link_libraries -

    target_link_libraries(my_library PRIVATE gcov)

then I don't get the errors.

What's the reason for the difference in behaviour? I thought that target_link_libraries(my_library PRIVATE gcov) would be equivalent to target_link_options(my_library PRIVATE -lgcov).


Solution

  • The answer is right there, in the docs:

    Note This command cannot be used to add options for static library targets, since they do not use a linker. To add archiver or MSVC librarian flags, see the STATIC_LIBRARY_OPTIONS target property.