Search code examples
makefilecmake

Are order-only prerequisites in GNU Makefile available in CMake and if not, what are the alternative options?


In GNU make, if a target A depend on two targets B and C, but using target C to build A requires that target B has already been built (target C itself doesn't depend on B however), I can use order-only prerequisites.

Are there any alternatives in CMake? I know CMake is just a configuration tool so the question may be better rephrased as "Can I write CMakeLists.txt in a way so that it generates Makefiles with order-only prerequisites?"

Alternative solutions are also welcome. Any help will be appreciated.


Solution

  • The typical case of using an order-only prerequisite is to make sure a directory is prepared before it is used in some make rule. Usually, cmake takes care of the directories for all the targets that are under it's control. But if you really need some directory, you can use a custom target command like this:

    add_custom_target(build-time-make-directory ALL
        COMMAND ${CMAKE_COMMAND} -E make_directory ${directory})
    

    This target is "with no output" so it will always be built, but the targets that depend on it won't necessarily be rebuilt.

    This is not limited to mkdir. Here is another example:

    add_executable(qqexe qq.c)
    add_custom_target(_custom_target COMMAND touch pp.c COMMENT pp)
    add_dependencies(qqexe _custom_target)
    

    Each time you run make, the timestamp of pp.c will refresh, but the qqexe will not be rebuilt unless the timestamp of qq.c changes.