Search code examples
visual-studiocmakecppcheck

Run custom target only when dependencies is modified


I'm using ADD_CUSTOM_TARGET to have my Visual Studio solution run cppcheck when being compiled:

ADD_CUSTOM_TARGET( STATIC_CODE_ANALYSIS_QUIET ALL COMMAND cppcheck ${PATH_TO_SOURCES}/src )

(this is a MCVE, I have more arguments actually)

The problem is that the tool is ran whenever I build the solution, even if I did not modify any file from my src folder. It makes no sense, it should only run when a file was modified.

So I tried to add a DEPENDS parameter:

set( STATIC_CODE_ANALYSIS_DEPENDENCIES )
list( APPEND STATIC_CODE_ANALYSIS_DEPENDENCIES "${PATH_TO_SOURCES}/src/main.cpp" )
ADD_CUSTOM_TARGET( STATIC_CODE_ANALYSIS_QUIET ALL COMMAND cppcheck ${PATH_TO_SOURCES}/src DEPENDS ${STATIC_CODE_ANALYSIS_DEPENDENCIES} )

But it makes no difference. I see the doc says "The target has no output file and is always considered out of date", so it's maybe intended. It looks like add_custom_command should be used to correctly handle "up to date"/"out to date" targets, however, cppcheck no being generating any "output file", I cannot create a "custom command" (which requires a OUTPUT parameter).

How can I have cppcheck be ran from Visual Studio automatically when I build the solution, but only if a file was modified since last run?

Note: using --output-file argument of cppcheck to use it as OUTPUT is not acceptable because then the output of the tool does not go to the Visual Studio console, which is required for the user to see if everything is OK or not.


Solution

  • As Tsyvarev suggested, let's do two COMMAND in custom command and create a timestamp file manually.

    # Static code analysis project:
    ADD_CUSTOM_COMMAND(
        OUTPUT           cppcheck.timestamp
        COMMAND          cppcheck
        ARGS             ${PATH_TO_SOURCES}/src
        COMMAND          date /t > cppcheck.timestamp
        COMMENT          "Running static code analysis..."
        VERBATIM
        DEPENDS          ${STATIC_CODE_ANALYSIS_DEPENDENCIES} )
    # Add module:
    ADD_CUSTOM_TARGET( STATIC_CODE_ANALYSIS
        ALL
        SOURCES cppcheck.timestamp )