CMake: build target library if any of the executab

2019-06-08 16:29发布

问题:

The layout of my project is as follow :

src/
    include/
           include1.h
           include2.h
           include3.h

    lib/
        lib1/
            source1_lib1.c
            source2_lib1.c
        lib2/
            source1_lib2.c
            source2_lib2.c
            source3_lib2.c
        lib3/
            source1_lib3.c
        lib4/
            source1_lib4.c
            source2_lib4.c

    module_A/ (this module will need lib1 and lib4)
            source1_moduleA.c
            source2_moduleA.c

    module_B/ (this module will need lib2 and lib3)
            source1_moduleB.c
            source2_moduleB.c
            source3_moduleB.c

    module_C/ (this module will need lib1, lib2, lib3 and lib4)
            source1_moduleC.c

    module_D/ (this module will need lib1 and lib3)
            source1_moduleD.c
            source2_moduleD.c
            source3_moduleD.c
            source4_moduleD.c

The global solution can be made by any number of module_X (it depends on the customer)

My project CMake file located under "/src" includes a configuration file (it is defined by a customer needs). This configuration file indicates which modules must be built and packaged to the target customer.

Let's say I have a customer X and the modules he selected are module_A and module_D. In this case my build system should only builds lib_1, lib_3 and lib_4.

What I am looking for is a way to define target libraries without being built until I do reference them in one the CMakeLists files under module_X directories.

Oh my bad I missed to say A BIG THANKS FOR YOUR HELP

回答1:

CMake can not do this out of the box. Any library that is added through an add_library call will be built.

But you can implement the behavior you want inside the CMake. Instead of calling add_library and add_executable directly you would call custom wrapper functions. The add_library wrapper simply stores the information required to call add_library, but does not call it directly. The add_executable wrapper iterates over all dependencies of the executable and makes the call to add_library if required.

You will have to design your own system for maintaining the state whether a particular library has already been added and what the parameters are for constructing the library target. Things get slightly more difficult when respecting transient dependencies as well (module_1 depends on lib_a which in turn depends on lib_b; but no executable depends on lib_b directly). But it is perfectly possible to build such a system with a few hundred lines of CMake code.



回答2:

cmake ..
make module_A module_D