Search code examples
c++cmakestatic-libraries

Ensure linker include specific files from static library


My goal is pretty much the same as that guy : Static initialization and destruction of a static library's globals

The solution to link library with linker flag --whole-archive works well (at least static instantiations are happening, but I am unsure about side effects). I'm not really satisfied by that one because you basically force every .o to be included in the final executable, plus you have to specify that you want to link it that way in the actual "consumer" of the lib :

target_link_libraries(my_exec
        PRIVATE -Wl,--whole-archive
        my_lib
        -Wl,--no-whole-archive // to ensure flags only apply to this dependency
)

Basically I am trying to achieve these two things :

  • Force include specific files rather than the whole archive
  • Make these specifications only known inside the static library CMake project. Bonus points if it is some kind of decorator that you write directly in the relevant .cpp files (Meaning you don't need to change anything to your cmake configuration to add or remove a file)

All resources found where about forcing the whole archive, there's close to nothing about granular control but maybe I am misusing the linker here. One of the main examples here.

Thanks for your time !


Solution

  • You can link the object files you want to always have in your final binary (exe or so) together into an object library.

    add_library(my_lib_always OBJECT file1.cpp file2.cpp)
    add_library(my_lib file3.cpp file4.cpp)
    

    Link to them both from your executable.

    target_link_libraries(my_exec PRIVATE my_lib_always my_lib)
    

    All definitions in my_lib_always get brought in, c.f. only the used definitions from my_lib.