### Install Bear on Debian/Ubuntu Source: https://github.com/cppcheck-opensource/cppcheck/blob/main/addons/doc/y2038.md Install the 'bear' tool on Debian or Ubuntu systems using apt-get. Bear is used to generate compile_commands.json for Make/Autotools projects. ```bash # On Debian/Ubuntu sudo apt-get install bear ``` -------------------------------- ### Install Cppcheck GUI and Resources Source: https://github.com/cppcheck-opensource/cppcheck/blob/main/gui/CMakeLists.txt Configures the installation of the cppcheck-gui executable, translation files, desktop entry, and icons to their respective destinations. It also adds dependencies for copying configuration, addons, and platform files. ```cmake install(TARGETS cppcheck-gui RUNTIME DESTINATION ${CMAKE_INSTALL_FULL_BINDIR} COMPONENT applications) install(FILES ${qms} DESTINATION ${CMAKE_INSTALL_FULL_BINDIR} COMPONENT applications) install(FILES cppcheck-gui.desktop DESTINATION ${CMAKE_INSTALL_DATAROOTDIR}/applications) # icons install(FILES cppcheck-gui.svg DESTINATION ${CMAKE_INSTALL_DATADIR}/icons/hicolor/scalable/apps) install(FILES cppcheck-gui.png DESTINATION ${CMAKE_INSTALL_DATADIR}/icons/hicolor/64x64/apps) add_dependencies(cppcheck-gui copy_cfg) add_dependencies(cppcheck-gui copy_addons) add_dependencies(cppcheck-gui copy_platforms) if (NOT DISABLE_DMAKE) add_dependencies(cppcheck-gui run-dmake) endif() if (BUILD_TESTING) add_subdirectory(test) endif() ``` -------------------------------- ### Install Bear on Fedora Source: https://github.com/cppcheck-opensource/cppcheck/blob/main/addons/doc/y2038.md Install the 'bear' tool on Fedora systems using dnf. Bear is used to generate compile_commands.json for Make/Autotools projects. ```bash # On Fedora sudo dnf install bear ``` -------------------------------- ### Analyze all configurations Source: https://github.com/cppcheck-opensource/cppcheck/blob/main/man/manual.md This command analyzes all possible preprocessor configurations for the given C file. All bugs in the example file will be found. ```bash cppcheck test.c ``` -------------------------------- ### Cppcheck Addon Execution Example Source: https://github.com/cppcheck-opensource/cppcheck/blob/main/man/manual-premium.md Execute Cppcheck addons using the --addon option. This example shows how to run the namingng.py addon. ```bash cppcheck --addon=namingng.py somefile.c ``` -------------------------------- ### Setup and Run Cppcheck CPU Donation Script Source: https://github.com/cppcheck-opensource/cppcheck/blob/main/readme.md This script sets up a Python virtual environment, installs dependencies, and runs the Cppcheck CPU donation script. It's used to analyze Debian source code and upload results for Cppcheck improvement. ```shell cd cppcheck/ python3 -m venv .venv source .venv/bin/activate pip install -r tools/donate-cpu-requirements.txt ./tools/donate-cpu.py ``` -------------------------------- ### Analyze configurations not defining A Source: https://github.com/cppcheck-opensource/cppcheck/blob/main/man/manual.md This command analyzes all configurations where 'A' is not defined. The last bug in the example file is found. ```bash cppcheck -UA test.c ``` -------------------------------- ### Cppcheck Dump Output Example Source: https://github.com/cppcheck-opensource/cppcheck/blob/main/man/writing-addons.md Example output from running cppcheck with the --dump flag, showing token strings and their associated ValueType information. ```text $ cppcheck --dump test.c $ python3 runaddon.py myaddon.py test.c.dump Checking 1.c.dump... Checking 1.c.dump, config ... short : None a : ValueType(type='short', sign='signed', bits=0, typeScopeId=None, originalTypeName=None, constness=0, pointer=0) ; : None a : ValueType(type='short', sign='signed', bits=0, typeScopeId=None, originalTypeName=None, constness=0, pointer=0) = : ValueType(type='short', sign='signed', bits=0, typeScopeId=None, originalTypeName=None, constness=0, pointer=0) a : ValueType(type='short', sign='signed', bits=0, typeScopeId=None, originalTypeName=None, constness=0, pointer=0) + : ValueType(type='int', sign='signed', bits=0, typeScopeId=None, originalTypeName=None, constness=0, pointer=0) 10 : ValueType(type='int', sign='signed', bits=0, typeScopeId=None, originalTypeName=None, constness=0, pointer=0) ; : None ``` -------------------------------- ### Preprocessor Defines Example Source: https://github.com/cppcheck-opensource/cppcheck/blob/main/gui/help/projectfiledialog.html Cppcheck automatically analyzes code with different preprocessor configurations. This example shows how defines like 'A' and 'B' are handled. ```c #ifdef A code1 #endif #ifdef B code2 #endif ``` -------------------------------- ### C Code Example for Variable Initialization Source: https://github.com/cppcheck-opensource/cppcheck/blob/main/man/writing-addons.md A basic C code snippet showing the declaration and initialization of an array. This example is used to demonstrate how variable information is represented and accessed by Cppcheck addons. ```c short a[10]; a[0] = 0; ``` -------------------------------- ### Enable Metrics Analysis Source: https://github.com/cppcheck-opensource/cppcheck/blob/main/man/manual-premium.md Add the --premium=metrics option to generate metrics, which are saved in the XML v3 report. This example also specifies XML version 3. ```bash cppcheck --premium=metrics test.c --xml-version=3 2> res.xml ``` -------------------------------- ### Install Bear on macOS Source: https://github.com/cppcheck-opensource/cppcheck/blob/main/addons/doc/y2038.md Install the 'bear' tool on macOS using Homebrew. Bear is used to generate compile_commands.json for Make/Autotools projects. ```bash # On macOS (using Homebrew) brew install bear ``` -------------------------------- ### Run Cppcheck and Generate XML Report Source: https://github.com/cppcheck-opensource/cppcheck/blob/main/gui/help/manual.html This example shows how to run Cppcheck with the --xml flag to generate an XML output file, which can then be used by the htmlreport tool. ```bash ./cppcheck gui/test.cpp --xml 2> err.xml ``` ```bash htmlreport/cppcheck-htmlreport --file=err.xml --report-dir=test1 --source-dir=. ``` -------------------------------- ### Generate HTML Report with Remote Source Repository Source: https://github.com/cppcheck-opensource/cppcheck/blob/main/man/manual.md This example shows how to generate an HTML report by linking to a remote GitHub/GitLab repository for source code, using a URL for the source directory. ```bash cppcheck gui/test.cpp --xml 2> err.xml cppcheck-htmlreport --file=err.xml --report-dir=test1 \ --source-dir=https://github.com///blob// ``` -------------------------------- ### Run misc addon Source: https://github.com/cppcheck-opensource/cppcheck/blob/main/addons/README.md This command runs the 'misc' addon on a C source file. Ensure the addon is installed and accessible. ```bash cppcheck --addon=misc src/test.c ``` -------------------------------- ### Generate HTML Report with Local Source Directory Source: https://github.com/cppcheck-opensource/cppcheck/blob/main/man/manual.md This example demonstrates generating an HTML report using a local Cppcheck XML output file and specifying the local source directory. ```bash cppcheck gui/test.cpp --xml 2> err.xml cppcheck-htmlreport --file=err.xml --report-dir=test1 --source-dir=. ``` -------------------------------- ### Analyze configuration -DA -DC Source: https://github.com/cppcheck-opensource/cppcheck/blob/main/man/manual.md This command analyzes only the configuration where both 'A' and 'C' are defined. The first bug in the example file is found. ```bash cppcheck -DA -DC test.c ``` -------------------------------- ### Running Cppcheck on a Single File Source: https://github.com/cppcheck-opensource/cppcheck/blob/main/man/manual-premium.md Demonstrates the basic command to run Cppcheck on a single C/C++ source file. This is the simplest way to start analyzing your code. ```bash cppcheck file1.c ``` -------------------------------- ### Resource Leak Example Source: https://github.com/cppcheck-opensource/cppcheck/blob/main/man/reference-cfg-format.md Demonstrates a resource leak in C code where a WinAPI function allocates a resource that is not freed. ```c void test() { HPEN pen = CreatePen(PS_SOLID, 1, RGB(255,0,0)); } ``` -------------------------------- ### ValueType Pointer Property Example Source: https://github.com/cppcheck-opensource/cppcheck/blob/main/man/writing-addons.md Illustrates how the 'pointer' property in ValueType increments with pointer indirection. ```text int p => pointer=0 int *p => pointer=1 int **p => pointer=2 ``` -------------------------------- ### C++ Code Example for Value Flow Analysis Source: https://github.com/cppcheck-opensource/cppcheck/blob/main/man/writing-addons.md Demonstrates a C++ function with conditional logic to illustrate how values can be 'known' or 'possible' at different points in the code. This example is used in conjunction with value flow analysis addons. ```cpp void foo(int x) // <- values of x is only constrained by data type. there are no "possible" or "known" values here. { a = x; // <- assuming that condition below is not redundant, x can have value 2. if (x == 2) { b = x + 2; // <- value of x is always 2 when this code is executed. It's "known". } else { c = x; } d = x + 10; // <- value of x can be 2 when this code is executed. It's "possible". } ``` -------------------------------- ### Enable Clang Parser (Experimental) Source: https://github.com/cppcheck-opensource/cppcheck/blob/main/man/manual-premium.md To use the experimental Clang parser instead of the default internal parser, install clang and use the --clang option. You can specify a custom Clang executable path or version with --clang=. ```bash cppcheck --clang ``` ```bash cppcheck --clang=clang-10 ``` -------------------------------- ### Force analysis of all configurations with -DA Source: https://github.com/cppcheck-opensource/cppcheck/blob/main/man/manual.md This command forces Cppcheck to test all configurations that define 'A'. The two initial bugs in the example file are found. ```bash cppcheck --force -DA test.c ``` -------------------------------- ### Debug Premium Addon License Validation (Windows) Source: https://github.com/cppcheck-opensource/cppcheck/blob/main/man/manual-premium.md Run the premiumaddon.exe with the --debug option on Windows to get detailed output about license validation issues. ```bash premiumaddon.exe --debug ``` -------------------------------- ### Displaying Scope for Each Token in Addons Source: https://github.com/cppcheck-opensource/cppcheck/blob/main/man/writing-addons.md This example shows how to iterate through each token in the `tokenlist` and print the type of the scope it belongs to. This is helpful for detailed token-level scope analysis. ```python import cppcheck @cppcheck.checker def func(cfg, data): for token in cfg.tokenlist: print(f'{token.str} : {scope.type}') ``` -------------------------------- ### Example Configuration for namingng.py Addon Source: https://github.com/cppcheck-opensource/cppcheck/blob/main/man/manual.md This JSON configuration defines naming conventions for variables, private members, and functions, including support for include guards and type prefixes. The default filename is namingng.config.json. ```json { "RE_VARNAME": ["[a-z]*[a-zA-Z0-9_]*\\Z"], "RE_PRIVATE_MEMBER_VARIABLE": null, "RE_FUNCTIONNAME": ["[a-z0-9A-Z]*\\Z"], "_comment": "comments can be added to the config with underscore-prefixed keys", "include_guard": { "input": "path", "prefix": "GUARD_", "case": "upper", "max_linenr": 5, "RE_HEADERFILE": "[^/].*\\.h\\Z", "required": true }, "var_prefixes": {"uint32_t": "ui32"}, "function_prefixes": {"uint16_t": "ui16", "uint32_t": "ui32"} } ``` -------------------------------- ### Debug Premium Addon License Validation (Linux/Mac) Source: https://github.com/cppcheck-opensource/cppcheck/blob/main/man/manual-premium.md Run the premiumaddon binary with the --debug option on Linux or Mac to get detailed output about license validation issues. ```bash premiumaddon --debug ``` -------------------------------- ### Example of Match Compiler Optimization Source: https://github.com/cppcheck-opensource/cppcheck/blob/main/tools/readme.md Illustrates the optimization performed by matchcompiler.py on a C++ file. The first function call to `Token::Match()` is optimized, while the second is not due to the string variable. ```cpp // lib/example.cpp void f1() { Token::Match(tok, "abc"); } void f2() { const char *abc = "abc"; Token::Match(tok, abc); } ``` ```cpp // build/example.cpp #include "token.h" #include "errorlogger.h" #include #include static const std::string matchStr1("abc"); // pattern: abc static bool match1(const Token* tok) { if (!tok || !(tok->str()==matchStr1)/* abc */) return false; return true; } void f1() { match1(tok); } void f2() { const char *abc = "abc"; Token::Match(tok, abc); } ``` -------------------------------- ### ValueType Constness Property Example Source: https://github.com/cppcheck-opensource/cppcheck/blob/main/man/writing-addons.md Demonstrates the bitmask representation of the 'constness' property in ValueType for various pointer and const declarations. ```text int * * => constness=0 const int * * => constness=1 int * const * => constness=2 int * * const => constness=4 const int * const * => constness=3 const int * const * const => constness=7 ``` -------------------------------- ### C++ Function Declaration and Definition Source: https://github.com/cppcheck-opensource/cppcheck/blob/main/man/writing-addons.md Illustrates a basic C++ function declaration and its definition with a call to another function. This serves as a foundational example for understanding code structure. ```cpp void foo(int x); void bar() { foo(1); } ``` -------------------------------- ### Fixed Ternary Operator Example (C++) Source: https://github.com/cppcheck-opensource/cppcheck/blob/main/man/checkers/duplicateExpressionTernary.md Demonstrates the correct usage of a ternary operator where different expressions are used in the branches, avoiding the duplicateExpressionTernary warning. ```cpp int result = condition ? x : y; // OK ``` -------------------------------- ### C Code Example for Scopes Source: https://github.com/cppcheck-opensource/cppcheck/blob/main/man/writing-addons.md A simple C code snippet illustrating the use of scopes, including nested blocks and conditional statements. This serves as input for testing scope-related addon functionalities. ```c int x; void foo() { if (x) { x = 0; } } ``` -------------------------------- ### Custom Platform Configuration XML Source: https://github.com/cppcheck-opensource/cppcheck/blob/main/man/manual.md An example of a custom XML platform configuration file for Cppcheck. This file defines properties like character bit size, default integer sign, and sizes of various data types. ```xml 8 signed 2 4 4 8 4 8 12 4 4 2 ``` -------------------------------- ### Example of Missing Type Information Source: https://github.com/cppcheck-opensource/cppcheck/blob/main/man/checkers/premium-misra-config.md This C++ code snippet illustrates how missing type definitions can lead to MISRA analysis failures. Ensure all custom types are properly defined before using them. ```cpp // Missing type information may prevent MISRA analysis typedef some_unknown_type my_type_t; // If some_unknown_type is not defined my_type_t variable; // MISRA rules cannot be properly checked ``` -------------------------------- ### Run addon with dump file and custom parameters Source: https://github.com/cppcheck-opensource/cppcheck/blob/main/addons/README.md This demonstrates how to run addons directly using Python, passing a Cppcheck dump file and custom parameters like '--rule-texts'. This method allows for more granular control and passing specific arguments to addons. ```bash cppcheck --dump --quiet src/test.c python misc.py src/test.c.dump python misra.py --rule-texts=~/misra_rules.txt src/test.c.dump ``` -------------------------------- ### Running Custom Addon with JSON Configuration Source: https://github.com/cppcheck-opensource/cppcheck/blob/main/man/manual.md Apply a custom addon using its JSON configuration file with the --addon option. ```bash cppcheck --addon=mychecks.json somefile.c ``` -------------------------------- ### Running misra.py Addon with Configuration Source: https://github.com/cppcheck-opensource/cppcheck/blob/main/man/manual.md Apply the misra.py addon with a specific JSON configuration file using the --addon option. ```bash cppcheck --addon=misra.json --enable=style somefile.c ``` -------------------------------- ### Semicolon Separated Undefines Source: https://github.com/cppcheck-opensource/cppcheck/blob/main/gui/help/projectfiledialog.html Undefines can be separated by semicolons for configuration. Example: A;C. ```text A;C ``` -------------------------------- ### Semicolon Separated Defines Source: https://github.com/cppcheck-opensource/cppcheck/blob/main/gui/help/projectfiledialog.html Defines can be separated by semicolons for configuration. Example: A;B=3;C. ```text A;B=3;C ``` -------------------------------- ### Generate Online Help Source: https://github.com/cppcheck-opensource/cppcheck/blob/main/gui/CMakeLists.txt If QHELPGENERATOR is available, this creates a custom target 'online-help.qhc' to generate the Qt Help Collection file from the specified source. It also adds a dependency on this target for the main GUI executable. ```cmake if (QHELPGENERATOR) # TODO: generate in CMAKE_BINARY_DIR folder add_custom_target(online-help.qhc ${QHELPGENERATOR} ${CMAKE_CURRENT_SOURCE_DIR}/help/online-help.qhcp -o ${CMAKE_CURRENT_SOURCE_DIR}/help/online-help.qhc) add_dependencies(cppcheck-gui online-help.qhc) endif() ``` -------------------------------- ### Specify License File Path Source: https://github.com/cppcheck-opensource/cppcheck/blob/main/man/manual-premium.md Use the --premium-license-file option to explicitly provide the path to your license file. This overrides the default search paths. ```bash cppcheck --premium-license-file=path/to/file.lic test.cpp ``` -------------------------------- ### Build Specific Configuration with CMake (Multi-Config Generators) Source: https://github.com/cppcheck-opensource/cppcheck/blob/main/readme.md Build a specific configuration like 'RelWithDebInfo' using CMake with multi-configuration generators. ```shell cmake -S . -B build cmake --build build --config RelWithDebInfo ``` -------------------------------- ### Basic C Code Example Source: https://github.com/cppcheck-opensource/cppcheck/blob/main/man/manual.md A simple C code snippet to demonstrate a basic array out-of-bounds error detection. ```c int main() { char a[10]; a[10] = 0; return 0; } ``` -------------------------------- ### Force Check More Configurations with Compilation Database Source: https://github.com/cppcheck-opensource/cppcheck/blob/main/man/manual.md When using a compilation database, use --force to check more configurations than the default single configuration. ```bash cppcheck --project=compile_commands.json --force ``` -------------------------------- ### Sample Cppcheck XML Report Structure Source: https://github.com/cppcheck-opensource/cppcheck/blob/main/man/manual-premium.md An example of the XML output generated by Cppcheck, detailing error information and locations. ```xml ``` -------------------------------- ### Example of Code Generating Error Source: https://github.com/cppcheck-opensource/cppcheck/blob/main/man/manual-premium.md This C code snippet demonstrates an array index out of bounds error that would typically be flagged by Cppcheck. ```c void f() { char arr[5]; arr[10] = 0; } ``` -------------------------------- ### Multi-line Output with Location Details Source: https://github.com/cppcheck-opensource/cppcheck/blob/main/man/manual.md Use --template and --template-location to display detailed information for warnings with multiple locations, including code context. ```c void f(int *p) { *p = 3; // line 3 } int main() { int *p = 0; // line 8 f(p); // line 9 return 0; } ``` ```bash cppcheck \ --template="{file}:{line}: {severity}: {message}\n{code}" \ --template-location="{file}:{line}: note: {info}\n{code}" multiline.c ``` -------------------------------- ### Inline Suppression Block Start Source: https://github.com/cppcheck-opensource/cppcheck/blob/main/man/manual.md Marks the beginning of a code block where specific warnings should be suppressed. Ensure a corresponding 'end' comment is used. ```c++ // cppcheck-suppress-begin aaaa ``` -------------------------------- ### Minimal windows.cfg for CreatePen Source: https://github.com/cppcheck-opensource/cppcheck/blob/main/man/reference-cfg-format.md A minimal configuration file to inform Cppcheck that CreatePen allocates a resource and DeleteObject deallocates it. ```xml CreatePen DeleteObject ``` -------------------------------- ### Cppcheck Addon for ValueType Analysis Source: https://github.com/cppcheck-opensource/cppcheck/blob/main/man/writing-addons.md An example Python addon that iterates through tokens and prints their ValueType. This requires the --dump flag during Cppcheck execution. ```python import cppcheck @cppcheck.checker def func(cfg, data): for token in cfg.tokenlist: print(f'{token.str} : {token.valueType}') ``` -------------------------------- ### Cppcheck Output for Error Example Source: https://github.com/cppcheck-opensource/cppcheck/blob/main/man/manual-premium.md This shows the typical output from Cppcheck when analyzing the provided code snippet that triggers an 'Array index out of bounds' error. ```text cppcheck test.c [test.c:3]: (error) Array 'arr[5]' index 10 out of bounds ``` -------------------------------- ### Build Specific Configuration with CMake (Single-Config Generators) Source: https://github.com/cppcheck-opensource/cppcheck/blob/main/readme.md Generate and build a specific configuration like 'RelWithDebInfo' using CMake with single-configuration generators. ```shell cmake -S . -B build_RelWithDebInfo -DCMAKE_BUILD_TYPE=RelWithDebInfo .. cmake --build build_RelWithDebInfo --config RelWithDebInfo ``` -------------------------------- ### Configuration for Executing Custom Addons Source: https://github.com/cppcheck-opensource/cppcheck/blob/main/man/manual.md This JSON configuration specifies the script to run and any arguments it requires. Use --addon=mychecks.json to apply this configuration. ```json { "script": "mychecks.py", "args": [ "--some-option" ], "ctu": false } ``` -------------------------------- ### Import Compilation Database Source: https://github.com/cppcheck-opensource/cppcheck/blob/main/man/manual.md Run Cppcheck using a generated compile_commands.json file. By default, only one configuration is checked. ```bash cppcheck --project=compile_commands.json ``` -------------------------------- ### Enable Bug Hunting Analysis Source: https://github.com/cppcheck-opensource/cppcheck/blob/main/man/manual-premium.md Use the --premium=bughunting option to enable noisy bug hunting analysis. This is intended for situations where accepting false positives is acceptable to find potential bugs. ```bash cppcheck --premium=bughunting ... ``` -------------------------------- ### Example of Recursive Template Code Source: https://github.com/cppcheck-opensource/cppcheck/blob/main/man/manual.md This C++ code demonstrates a recursive template that can lead to excessive instantiation and potentially slow analysis or high memory usage by Cppcheck. ```cpp template void a() { a(); } void foo() { a<0>(); } ``` -------------------------------- ### Configuration for misra.py Addon Source: https://github.com/cppcheck-opensource/cppcheck/blob/main/man/manual.md This JSON configuration file specifies the misra.py script and its arguments for loading MISRA C 2012 rule texts. Use --addon=misra.json to apply this configuration. ```json { "script": "misra.py", "args": [ "--rule-texts=misra_c_2012__headlines_for_cppcheck - AMD1+AMD2.txt" ], "ctu": true } ``` -------------------------------- ### C-style Cast Warning Source: https://github.com/cppcheck-opensource/cppcheck/blob/main/man/checkers/dangerousTypeCast.md This example demonstrates an unsafe C-style cast that can lead to invalid type conversions. Use C++ casts like `dynamic_cast` for safer alternatives. ```cpp struct Base{}; struct Derived: public Base {}; void foo(Base* base) { Derived *p = (Derived*)base; // <- can be invalid } ``` -------------------------------- ### Analyze Visual Studio Solution Source: https://github.com/cppcheck-opensource/cppcheck/blob/main/man/manual.md Run Cppcheck on an entire Visual Studio solution file (.sln). All available configurations in the project(s) will be analyzed. ```bash cppcheck --project=foobar.sln ``` -------------------------------- ### Displaying Remarks in Cppcheck Text Output Source: https://github.com/cppcheck-opensource/cppcheck/blob/main/man/manual.md Use the --template option with {remark} to show justifications in the text output. This example demonstrates how to display the remark for an 'unreadVariable' warning. ```bash $ ./cppcheck --enable=style \ --template="{file}:{line}: {message} [{id}]\n{remark}" test1.c ``` -------------------------------- ### Display Help Screen for cppcheck-htmlreport Source: https://github.com/cppcheck-opensource/cppcheck/blob/main/man/manual.md This command shows the available options and usage instructions for the `cppcheck-htmlreport` script. ```bash htmlreport/cppcheck-htmlreport -h ``` -------------------------------- ### Recommended Release Build with GNU Make Source: https://github.com/cppcheck-opensource/cppcheck/blob/main/readme.md Build Cppcheck with optimizations, rules support, and specified file directory using GNU Make. ```shell make MATCHCOMPILER=yes FILESDIR=/usr/share/cppcheck HAVE_RULES=yes CXXOPTS="-O2" CPPOPTS="-DNDEBUG" ``` -------------------------------- ### Cppcheck Template Recursion Output Source: https://github.com/cppcheck-opensource/cppcheck/blob/main/man/manual-premium.md Example output from Cppcheck when template recursion limits are reached. It indicates the template instantiation that caused the issue and suggests limiting Cppcheck recursion. ```text test.cpp:4:5: information: TemplateSimplifier: max template recursion (100) reached for template 'a<101>'. You might want to limit Cppcheck recursion. [templateRecursion] a(); ^ ``` -------------------------------- ### Define test-projectfile executable and its dependencies Source: https://github.com/cppcheck-opensource/cppcheck/blob/main/gui/test/projectfile/CMakeLists.txt This snippet defines the test-projectfile executable, lists its source files, and sets up include directories, compile definitions, and linked libraries. It also adds dependencies for building and testing. ```cmake qt_wrap_cpp(test-projectfile_SRC testprojectfile.h ${CMAKE_SOURCE_DIR}/gui/projectfile.h) add_custom_target(build-projectfile-deps SOURCES ${test-projectfile_SRC}) add_dependencies(gui-build-deps build-projectfile-deps) add_executable(test-projectfile ${test-projectfile_SRC} testprojectfile.cpp ${CMAKE_SOURCE_DIR}/gui/common.cpp ${CMAKE_SOURCE_DIR}/gui/projectfile.cpp ) target_include_directories(test-projectfile PRIVATE ${CMAKE_SOURCE_DIR}/gui ${CMAKE_SOURCE_DIR}/lib) target_compile_definitions(test-projectfile PRIVATE SRCDIR="${CMAKE_CURRENT_SOURCE_DIR}") target_link_libraries(test-projectfile ${QT_CORE_LIB} ${QT_TEST_LIB}) ``` -------------------------------- ### C++ Code Example for Unused Return Value Source: https://github.com/cppcheck-opensource/cppcheck/blob/main/man/reference-cfg-format.md This C++ code shows a potential bug where the return value of `strcmp` is ignored. Cppcheck can flag this if `strcmp` is configured with the directive. ```cpp bool test(const char* a, const char* b) { strcmp(a, b); // <- bug: The call of strcmp does not have side-effects, but the return value is ignored. return true; } ``` -------------------------------- ### C++ Code Example for Uninitialized Variable Detection Source: https://github.com/cppcheck-opensource/cppcheck/blob/main/man/reference-cfg-format.md This C++ code demonstrates a scenario where an uninitialized variable might be used if a function does not return. Cppcheck can detect this if the function is configured with . ```cpp void test(int x) { int data, buffer[1024]; if (x == 1) data = 123; else ZeroMemory(buffer, sizeof(buffer)); buffer[0] = data; // <- error: data is uninitialized if x is not 1 } ``` -------------------------------- ### Use Clang Parser Source: https://github.com/cppcheck-opensource/cppcheck/blob/main/man/manual.md Command to enable the experimental Clang parser for Cppcheck analysis. ```bash cppcheck --clang ``` -------------------------------- ### Cppcheck Exception Safety Check Example Source: https://github.com/cppcheck-opensource/cppcheck/blob/main/gui/help/manual.html Demonstrates a scenario where throwing an exception can lead to undefined behavior due to deallocated memory. Cppcheck identifies this issue with specific enable flags. ```bash cppcheck --enable=exceptNew --enable=exceptRealloc except2.cpp ``` ```text [except2.cpp:7]: (error) Throwing exception in invalid state, p points at deallocated memory ``` -------------------------------- ### Configure CMake for Release Builds and Testing Source: https://github.com/cppcheck-opensource/cppcheck/blob/main/readme.md Flags for creating optimized release builds and enabling testing during CMake configuration. ```shell cmake -S . -B build -DUSE_MATCHCOMPILER=ON cmake -S . -B build -DBUILD_TESTING=ON ``` -------------------------------- ### Define Library Sources and Headers Source: https://github.com/cppcheck-opensource/cppcheck/blob/main/externals/simplecpp/CMakeLists.txt Uses file GLOB to find all header and source files in the current directory for library creation. ```cmake file(GLOB hdrs "*.h") file(GLOB srcs "*.cpp") add_library(simplecpp ${srcs} ${hdrs}) ``` -------------------------------- ### Project-wide analysis with y2038 addon Source: https://github.com/cppcheck-opensource/cppcheck/blob/main/addons/README.md Perform project-wide analysis using a compile_commands.json file and the 'y2038' addon. This is useful for large projects where build system integration is available. ```bash cppcheck --project=build/compile_commands.json --addon=y2038 ``` -------------------------------- ### C++ Code with Unused Variable and Scope Issues Source: https://github.com/cppcheck-opensource/cppcheck/blob/main/gui/help/manual.html A C++ code example that contains an unused variable and a scope that could be reduced. When --enable=style is used, Cppcheck reports these stylistic issues. ```cpp void f(int x) { int i; if (x == 0) { i = 0; } } ``` -------------------------------- ### C++ Code Example for Unreachable Code Detection Source: https://github.com/cppcheck-opensource/cppcheck/blob/main/man/reference-cfg-format.md This C++ code demonstrates a situation where unreachable code might occur due to redundant checks. If 'calculate' is marked as , Cppcheck can detect this redundancy. ```cpp void f(int x) { if (calculate(x) == 213) { } else if (calculate(x) == 213) { // unreachable code } } ``` -------------------------------- ### Checking All Source Files in a Folder with Cppcheck Source: https://github.com/cppcheck-opensource/cppcheck/blob/main/gui/help/manual.html Illustrates how to use Cppcheck to analyze all source files within a specified directory. This is a common use case for projects with multiple source files. ```bash cppcheck path ``` -------------------------------- ### Using dynamic_cast for Safe Casting Source: https://github.com/cppcheck-opensource/cppcheck/blob/main/man/checkers/dangerousTypeCast.md This example shows the recommended C++ approach using `dynamic_cast` to safely convert a base class pointer to a derived class pointer. This ensures the conversion is valid at runtime. ```cpp struct Base{}; struct Derived: public Base {}; void foo(Base* base) { Derived *p = dynamic_cast(base); } ``` -------------------------------- ### Include Project Subdirectories Source: https://github.com/cppcheck-opensource/cppcheck/blob/main/CMakeLists.txt Includes various subdirectories of the project, such as 'externals/simplecpp', 'externals/picojson', 'lib', 'frontend', 'cli', 'test', 'gui', and 'tools'. This organizes the build process for different components. ```cmake add_subdirectory(externals/simplecpp) add_subdirectory(externals/picojson) add_subdirectory(lib) # CppCheck Library add_subdirectory(frontend) add_subdirectory(cli) # Client application add_subdirectory(test) # Tests add_subdirectory(gui) # Graphical application add_subdirectory(tools) ``` -------------------------------- ### C Code Example for Special Tokenlist Tweaks Source: https://github.com/cppcheck-opensource/cppcheck/blob/main/man/writing-addons.md This C code demonstrates a scenario with an 'else if' structure where Cppcheck might implicitly add braces to the tokenlist. It highlights how Cppcheck handles optional braces around single statements. ```c void foo(int x) { if (x > 0) --x; else if (x < 0) ++x; } ``` -------------------------------- ### Identify Static Member Functions in C++ Source: https://github.com/cppcheck-opensource/cppcheck/blob/main/man/checkers/functionStatic.md This example demonstrates member functions that do not access non-static members or call non-static functions, making them candidates for the 'static' keyword. Add 'static' to the declaration to indicate independence from object instances. ```cpp class Calculator { public: int add(int a, int b) { return a + b; // Only uses parameters } void printMessage() { std::cout << "Hello World" << std::endl; // Uses no instance data } bool isValidNumber(int num) { return num > 0 && num < 1000; // Pure function } }; ``` ```cpp class Calculator { public: static int add(int a, int b) { return a + b; // Can be called as Calculator::add(5, 3) } static void printMessage() { std::cout << "Hello World" << std::endl; // Can be called without instance } static bool isValidNumber(int num) { return num > 0 && num < 1000; // Clearly indicates no state dependency } }; ``` -------------------------------- ### Configuration for fopen, freopen, and fclose Source: https://github.com/cppcheck-opensource/cppcheck/blob/main/man/reference-cfg-format.md Configures Cppcheck for standard C library functions fopen, freopen, and fclose, specifying reallocation arguments. ```xml fopen freopen fclose ``` -------------------------------- ### Analyze Visual Studio 2026 Solution Source: https://github.com/cppcheck-opensource/cppcheck/blob/main/man/manual.md Run Cppcheck on an entire Visual Studio 2026 solution file (.slnx). All available configurations in the project(s) will be analyzed. ```bash cppcheck --project=foobar.slnx ``` -------------------------------- ### Basic C++ Code Example with Array Out-of-Bounds Error Source: https://github.com/cppcheck-opensource/cppcheck/blob/main/gui/help/manual.html Demonstrates a simple C++ code snippet that triggers an array out-of-bounds error, which Cppcheck can detect. This is useful for initial testing and understanding Cppcheck's error reporting. ```cpp int main() { char a[10]; a[10] = 0; return 0; } ``` -------------------------------- ### Analyze Visual Studio Project Source: https://github.com/cppcheck-opensource/cppcheck/blob/main/man/manual.md Run Cppcheck on an individual Visual Studio project file (.vcxproj). All available configurations in the project(s) will be analyzed. ```bash cppcheck --project=foobar.vcxproj ``` -------------------------------- ### Configure CMake for GUI and Rules Source: https://github.com/cppcheck-opensource/cppcheck/blob/main/readme.md Flags to enable the GUI application and rule support (requires PCRE) during CMake configuration. ```shell cmake -S . -B build -DBUILD_GUI=ON cmake -S . -B build -DHAVE_RULES=ON ``` -------------------------------- ### Example #error Directive in C/C++ Source: https://github.com/cppcheck-opensource/cppcheck/blob/main/man/checkers/preprocessorErrorDirective.md This is a standard C/C++ preprocessor directive that explicitly causes a compilation error. It's typically used to halt compilation if certain conditions, like an undefined byte order, are met. The code itself is correct and should not be altered. ```cpp #ifndef __BYTE_ORDER__ error Byte order is not defined #endif ``` -------------------------------- ### Build and Run dmake Tool Source: https://github.com/cppcheck-opensource/cppcheck/blob/main/tools/readme.md Builds and executes the dmake tool, which automatically generates the main Makefile for Cppcheck. The main Makefile should not be modified manually. ```shell cd path/to/cppcheck make dmake ./dmake ``` -------------------------------- ### Activate Misra C 2012 Checkers Source: https://github.com/cppcheck-opensource/cppcheck/blob/main/man/manual-premium.md Enable Misra C 2012 coding standard checkers with the --premium=misra-c-2012 option. ```bash cppcheck --premium=misra-c-2012 ... ``` -------------------------------- ### Configure DLL Export/Import Definitions Source: https://github.com/cppcheck-opensource/cppcheck/blob/main/externals/simplecpp/CMakeLists.txt Sets preprocessor definitions for DLL export and import, essential for Windows dynamic linking. ```cmake target_dll_compile_definitions(simplecpp EXPORT SIMPLECPP_EXPORT IMPORT SIMPLECPP_IMPORT) ``` -------------------------------- ### Convert Makefile to Compilation Database with Bear Source: https://github.com/cppcheck-opensource/cppcheck/blob/main/man/manual.md Use the 'bear' utility on Linux to convert a Makefile into a compile_commands.json file, which can then be imported by Cppcheck. ```bash bear -- make ``` -------------------------------- ### Import Cppcheck GUI Project Source: https://github.com/cppcheck-opensource/cppcheck/blob/main/man/manual.md Import a Cppcheck GUI project file (.cppcheck) into the command-line tool to utilize GUI-specific options not directly available on the command line. ```bash cppcheck --project=foobar.cppcheck ``` -------------------------------- ### Use Custom Clang Executable Source: https://github.com/cppcheck-opensource/cppcheck/blob/main/man/manual.md Command to specify a custom Clang executable for the experimental Clang parser. ```bash cppcheck --clang=clang-10 ``` -------------------------------- ### Running a Custom Addon Script Source: https://github.com/cppcheck-opensource/cppcheck/blob/main/man/manual.md Execute a custom addon script, such as 'mychecks.py', using the --addon option. This can be a direct script path or a JSON configuration file. ```bash cppcheck --addon=namingng.py somefile.c ``` ```bash cppcheck --addon=mychecks.py somefile.c ``` -------------------------------- ### Expert Build with g++ Source: https://github.com/cppcheck-opensource/cppcheck/blob/main/readme.md Direct compilation command using g++ for building Cppcheck without dependencies. Requires C++11 support. ```cpp g++ -o cppcheck -std=c++11 -Iexternals -Iexternals/simplecpp -Iexternals/tinyxml2 -Iexternals/picojson -Ilib -Ifrontend frontend/*.cpp cli/*.cpp lib/*.cpp externals/simplecpp/simplecpp.cpp externals/tinyxml2/tinyxml2.cpp ``` -------------------------------- ### Limit analysis to 2 configurations with X defined Source: https://github.com/cppcheck-opensource/cppcheck/blob/main/man/manual.md This command limits the analysis to a maximum of 2 valid preprocessor configurations, specifically those where 'X' is defined. Bugs will be found within these configurations. ```bash cppcheck --max-configs=2 -DX test.c ```