Menu

Precompiled headers with compilation database

2023-08-30
2023-08-30
  • Samuel Poláček

    I am using precompiled headers in my project and I have observed that Cppcheck does not seem to work with them even though the information about precompiled headers is in compile_commands.json.

    Simplified related piece of compile_commands.json.

    {
      "directory": "/<path_to_proj_root>/<project>/build",
      "command": "/usr/bin/c++ <defines and options...> -Winvalid-pch -Xclang -include-pch -Xclang /<path_to_proj_root>/<project>/build/src/<target>/CMakeFiles/<target>.dir/cmake_pch.hxx.pch -Xclang -include -Xclang /<path_to_proj_root>/<project>/build/src/<target>/CMakeFiles/<target>.dir/cmake_pch.hxx -o src/<target>/CMakeFiles/<target>.dir/main.cpp.o -c /<path_to_proj_root>/<project>/src/<target>/main.cpp",
      "file": "/<path_to_proj_root>/<project>/src/<target>/main.cpp"
    }
    

    Cppcheck does not parse -include from compile_commands.json (see ImportProject::FileSettings::parseCommand()).

    From Cmake's doc:

    The list of header files is used to generate a header file named cmake_pch.h|xx which is used to generate the precompiled header file (.pch, .gch, .pchi) artifact. The cmake_pch.h|xx header file will be force included (-include for GCC, /FI for MSVC) to all source files, so sources do not need to have #include "pch.h".

    The last part is important - CMake force includes the precompiled header so you don't have to, i.e., CMake allows us to compile code that would not compile if you turned precompiled headers off. Precompiled headers are a convenience feature and projects should, in an ideal world, be able to compile with precompiled turned off, however, that is seldom the case.

    The only solution, with Cppcheck 2.11, I can think of, is to make project compile with precompiled headers turned off. This might require a bit of work on project's side.

     

    Last edit: Samuel Poláček 2023-08-30
  • Samuel Poláček

    This might be a way to disable precompiled headers in root CMakeLists.txt

    option(ENABLE_PRECOMPILED_HEADERS "Enable precompiled headers" ON)
    if (NOT ENABLE_PRECOMPILED_HEADERS)
        message(WARNING "Precompiled headers are disabled.")
    
        # Define a dummy target_precompile_headers function to override the CMake's one.
        function(target_precompile_headers)
            message(AUTHOR_WARNING "target_precompile_headers has no effect for ${ARGV0} target.")
        endfunction()
    endif()
    
     

    Last edit: Samuel Poláček 2023-08-30

Log in to post a comment.

Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.