-->

Do something for all targets

2020-08-08 10:36发布

问题:

What is the best way to do additional stuff for all (binary) targets?

Examples:

  • I want to check that each library name follows a pattern.
  • I want to sign each executable.

I dont what the C/C++ developers to use nonstandard commands (like add_library2). I want them to use and learn the official CMake functions, but have them do additonal, project specific, stuff.

回答1:

The built-in CMake functions add_library and add_executable can be overidden by defining CMake functions of the same name. E.g., to automatically sign all added executables add the following code:

function (add_executable _name)
    _add_executable(${ARGV})
    if (TARGET ${_name})
        add_custom_command(TARGET ${_name} POST_BUILD
            COMMAND sign_executable $<TARGET_FILE:${_name}>)
    endif()
endfunction()

The original built-in add_executable can be invoked by prefixing it with an underscore character. The same pattern can be applied to add_library to check the name of the library.



回答2:

You can overwrite any CMake command/function to extend its functionality, but please

Call Things by their Names

I strongly advocate to call the things by their names and not doing things implicitly. It will be easier for everybody using/maintaining/debugging your CMake based project.

If you want to sign your executable - and that's probably even platform specific - you create a function like add_post_build_step_sign_executable() which would add the appropriate post build steps:

add_executable(MyExe main.cpp)
if (WIN32)
    add_post_build_step_sign_executable(MyExe)
endif()

And if you have to repeat yourself too often put that code snippet into a function like my_project_add_signed_executable() itself. It could still have the same parameter syntax as CMake's add_executable() command.

Runtime Checks vs. Static Code Analysis

Regarding library naming checks, I see this more like checking against your project's CMake script coding styles and would not use runtime checks for this.

For example you could use something like cmake-lint or your own external script to check for conformity.

References

  • How to frame the concept behind CMake?
  • cmake: get add_library() names
  • How to ensure consistent coding style for CMakeLists.txt and FindXXX.cmake


标签: cmake