Static code checker for C++

Overview

cpplint - static code checker for C++

https://travis-ci.org/cpplint/cpplint.svg?branch=master

Cpplint is a command-line tool to check C/C++ files for style issues following Google's C++ style guide. Cpplint is developed and maintained by Google Inc. at google/styleguide, also see the wikipedia entry

While Google maintains cpplint, Google is not (very) responsive to issues and pull requests, this fork aims to be (somewhat) more open to add fixes to cpplint to enable fixes, when those fixes make cpplint usable in wider contexts. Also see discussion here https://github.com/google/styleguide/pull/528.

Installation

To install cpplint from PyPI, run:

$ pip install cpplint

Then run it with:

$ cpplint [OPTIONS] files

For full usage instructions, run:

$ cpplint --help

Changes

The modifications in this fork are minor fixes and cosmetic changes, such as:

  • python 3 compatibility
  • more default file extensions
  • customizable file extensions with the --extensions argument
  • continuous integration on travis
  • support for recursive file discovery via the --recursive argument
  • support for excluding files via --exclude
  • JUnit XML output format
  • Overriding repository root auto-detection via --repository
  • Support #pragma once as an alternative to header include guards
  • ... and a few more (most of which are open PRs on upstream)

Acknowledgements

Thanks to Google Inc. for open-sourcing their in-house tool. Thanks to maintainers of the fork

Comments
  • Move project to cpplint/cpplint

    Move project to cpplint/cpplint

    If we move the project to a organisation we can have multiple collaborators on the project and share the maintenance. We use this version of cpplint internally at work and would happily spend time maintaining the project, issues and PRs.

    opened by mattyclarkson 10
  • Add language about Unix directory aliases (fixes #139)

    Add language about Unix directory aliases (fixes #139)

    Thanks for this great project! cpplint has helped us a lot in LightGBM.

    This pull request attempts to address https://github.com/cpplint/cpplint/issues/139#issuecomment-629594423. See the conversation on that issue for background.

    Essentially, if something.cpp uses #include "./something.h", it can generate the warning

    src/foo.cpp:2: src/something.cpp should include its header file src/something.h [build/include] [5]

    That message might be confusing to people (like me) who didn't know that Unix directory aliases like ./ are not allowed by the Google style guide.

    This PR adds a more informative warning for such cases.

    Thanks for your time and consideration!

    opened by jameslamb 9
  • --exclude not work on Windows with cpplint 1.4.4 Python 3.7.3

    --exclude not work on Windows with cpplint 1.4.4 Python 3.7.3

    I'm trying to use cpplint for code static analysis and here I'm in the trouble with excluded directories :(

    Long time ago I used a batch script to list all directory and files into a file list and feed cpplint to get the results, but there's distadvantages that when the files it too many it'll overflow the max length of command line to work.

    I've already try to use all the follow code, but none works:

    cpplint --root=src --filter=-build/include_subdir,-build/c++11 --repository=src --recursive  --exclude=src/third_party/* src
    
    cpplint --root=src --filter=-build/include_subdir,-build/c++11 --repository=src --recursive  --exclude=src/third_party/*/* src
    
    cpplint --root=src --filter=-build/include_subdir,-build/c++11 --repository=src --recursive  --exclude=src/third_party/*/* --exclude=src/third_party/* --exclude=src/third_party/*/*/* src
    

    cpplint always lint the very src/third_party directory, please help me, I'm struggling with this issue about several weeks. Hopeless :(

    Remark:

    cpplint is installed by:

    pip install cpplint
    
    opened by universeroc 9
  • Linux system headers not detected as system headers

    Linux system headers not detected as system headers

    PR #133 swapped the dynamic system header detection from <> brackets to a hard coded list of names. This causes false positives in files with Linux specific includes. Unless I'm mistaken and files under /usr/include should not be classified as system headers.

    test.h

    // Copyright 2020 Open Networking Foundation
    // SPDX-License-Identifier: Apache-2.0
    
    #ifndef _PRIVATE_TMP_TEST_H_
    #define _PRIVATE_TMP_TEST_H_
    
    #include <net/ethernet.h>
    
    #include <vector>
    
    #include "absl/base/thread_annotations.h"
    
    #endif  // _PRIVATE_TMP_TEST_H_
    
    # cpplint test.h
    test.h:9:  Found C++ system header after other system header. Should be: test.h, c system, c++ system, other.  [build/include_order] [4]
    Done processing test.h
    Total errors found: 1
    
    opened by pudelkoM 8
  • add elif as an exception for CheckSpacingForFunctionCall()

    add elif as an exception for CheckSpacingForFunctionCall()

    The current version of the code allows for white spaces after preprocessor directive #if (FOO == 1) but not after #elif (FOO == 1).

    The code below will throw this error: test.cpp:4: Extra space before ( in function call [whitespace/parens] [4]

    int main() {
    #if (A == 0)
        foo();
    #elif (A == 1)
        bar();
    #endif
    return 0;
    }
    

    This pull request fixes that.

    opened by Migelo 7
  • Update cpplint.py to r456 - rebased

    Update cpplint.py to r456 - rebased

    So this is my attempt at fixing the merge conflict in #19. I guess this may break several tests, so there may be several iterations to do. The main conflicts to solve were about the _IsSourceExtension() function and the _test_suffixes variable.

    As a sidenote, it would be nicer to keep the git history clean, by fetching commit from the google styleguide and making a merge commit, where the merge result would be something like this PR.

    456 - Tweak lint to sometimes allow { on line following array initialization. 455 - Recognize more types. 454 - Try a bit harder to detect templated types. 453 - Changed error message wording on build/storage_class to be less ambiguous. 452 - Recognize more types to silence false positives for brace warnings. 451 - 450 - 449 - Ignore whitespace/tab for Linux Kernel files. 448 - Remove some more false positive lint warnings for int64{n}. 447 - Just one warning message for line length is enough, don't need two. 446 - Allow braced conversions to int16, uint64, etc. per the style guide. 445 - Fixed handling of backslash escapes for checking whether a "//" is quoted. 444 - Reduced dependency on hardcoded .cc extension. 443 - Disable single-arg constructor checks by default, since ClangTidy has the same check. We could just delete the check entirely, but it's slightly useful in places that can't run ClangTidy. 442 - Fix matching of macro names in CheckTrailingSemicolon to include digits. 441 - Deleted checks: - All checks for RValue references. - Spacing check around boolean &&, because those look like RValue references. A huge amount of code and effort were dedicated to tell RValue references apart from boolean expressions, and to differentiate allowed versus banned RValue references. But we still get regular false positives from this one check. Rather than making the check more complex than what it already is, it seemed safer to just delete it altogether for now, and have a different process for catching RValue references. 440 - Add rule to cpplint to throw error on empty if statement bodies without else clauses. If statement bodies with comments are not considered empty. 439 - Allow spaces before closing brace of namespace block so that namespaces inside of macro definitions (where the entire macro definition is indented) are not treated as errors. 438 - cpplint: fix a false positive on new const int(x). 437 - Only check for function length when current line is inside a function. 436 - cpplint: Catch static std::string instances as well as those written as string. Previously users would sometimes work around the lint warning by changing their code to even worse code by adding the "std::" prefix. 435 - cpplint: Be a little smarter about warning on indentation. 434 - cpplint: Remove false positives on some functions returning string const&. 433 - cpplint: improve diagnostics of global/static string objects. 432 - Allow non-const reference parameters for iostream based types. 431 - Better handling of raw strings inside comments. 430 - 429 - 428 - 427 - Add support to CHECK_NOTNULL when checking if a member variable is initialized with itself. 426 - Allow suppressing specific warnings in C headers. 425 - Allow spaces before parens for inline assembly. 424 - Remove lint checks for {EXPECT,ASSERT}_.*_M. 423 - Allow comment lines of more than 80 characters if they contain a single "word" (without any spaces). 422 - cpplint: Warn on inclusion of C++14 headers. 421 - cpplint: recognize <shared_mutex> as a standard library header. 420 - Add <scoped_allocator> to cpplint's list of C++ standard headers. 419 - Add cpplint check for tr1/ headers. We removed the nanny guards for these 418 - 417 - Update the styleguide and cpplint to allow unnamed parameters 416 - Remove the rule explicitly banning non-default move operations. 415 - Remove the check for explicit multi arg constructors 414 - Include clarity of lambda default captures in "pros" section, mention of capturing this and lambdas which escape the current scope in "cons". Soften the ban on default captures to a preference, with admonition against using them for capturing this or when they will escape the current scope. This is a fairly straightforward change with a brief inclusion of 2 problematic cases for implicit capture. As this is the style guide, I'm not sure how much more detail is appropriate. 413 - Fixed a bug by making regex in CleanseRawStrings match multiple raw strings on a single line in left-to-right order. 412 - Fixed false positive for classes derived using decltype() 411 - 410 - Recognize '1LL<<20' as numeric and don't flag it for spacing.

    Conflicts:

    cpplint.py

    cpplint_unittest.py

    Conflicts:

    cpplint.py

    cpplint_unittest.py

    opened by tkruse 7
  • Fix issue when function arguments with mutiply class or struct keywords

    Fix issue when function arguments with mutiply class or struct keywords

    Issue introduction: CPPLint already have protection when function arguments with extra "class" or "struct" keywords, following scenario is fine:

          struct demo_struct {
              int field;
          };
          
          void demo_issue(int num,
              struct demo_struct const *new_struct1,
              )
          {
              return 0;
          }
    

    But in case multiply "struct" function arguments existed in a function like below(add "new_struct2" parameter):

          struct demo_struct {
              int field;
          };
          
          void demo_issue(int num,
              struct demo_struct const *new_struct1,
              struct demo_struct const *new_struct2  
              )
          {
              return 0;
          }
    

    It will cause false positive reporting as below: demo.cpp:11: Closing brace should be aligned with beginning of struct demo_struct [whitespace/indent] [3]

    Issue analysis: In case meet multiply struct parameters, will push "_ClassInfo" instances mutiply times into the "stack" array of NestingState class , when ";" or ")" token is encountered before OpenBrace is not seen, will pop ONLY one "_ClassInfo" instance from the stack. that makes at least one "struct" parameters be regarded as a "_ClassInfo" block but not a "struct" parameter. Then produce above warning.

    Issue reslove: Greedy pop the "_ClassInfo" instance from the stack until "_ClassInfo" instance have open brace when ";" or ")" token is encountered.

    opened by yanj403 6
  • in 1.4.1 getting 'Uncommented text after #endif is non-standard.  Use a comment.'

    in 1.4.1 getting 'Uncommented text after #endif is non-standard. Use a comment.'

    We get a failure on every #endif with 1.4.1 I think the following rege is wrong as it marks a line contianing only '#endif' (with no other characters) as a failure

      if Match(r'\s*#\s*endif\s*([^/\s]|/[^/]|$)', line):
        error(filename, linenum, 'build/endif_comment', 5,
              'Uncommented text after #endif is non-standard.  Use a comment.')
    
    opened by PhracturedBlue 6
  • Please merge with main branch to enable style check on .cu and .cuh files

    Please merge with main branch to enable style check on .cu and .cuh files

    Is it possible to update the cpplint.py from google (the main branch)? I am mainly looking for the style check feature on cuda source and header files (.cu and .cuh). Will be awesome to see this in the cpplint for pip install.

    opened by jasjuang 6
  • Running cpplint on Windows 10 cmd.exe results in

    Running cpplint on Windows 10 cmd.exe results in "failed to create process"

    The cpplint console entry point (cpplint.exe) does not seem to be working on Windows 10 with Python 3.5.

    >python -m venv venv
    >cd venv
    >Scripts\activate.bat
    (venv) >python -V
    Python 3.5.1
    (venv) >pip install cpplint
    Collecting cpplint
      Using cached cpplint-0.0.6.tar.gz
    Installing collected packages: cpplint
      Running setup.py install for cpplint
    Successfully installed cpplint-0.0.6
    (venv) >cpplint
    failed to create process.
    

    The same behavior happens outside of a venv.

    opened by johnthagen 6
  • Handle Other Header Files for Build Include Subdir

    Handle Other Header Files for Build Include Subdir

    build/include_subdir should handle arbitrarily header file extensions.

    Tests

    #include "test.hh" // now emits warning with default header extensions
    #include "test.h"  // same warning with default header extensions
    #include "test.aa" // can emit warning if .aa is set as header extension
    
    opened by geoffviola 5
  • avoid false positives on transform issue27

    avoid false positives on transform issue27

    This PR addresses https://github.com/cpplint/cpplint/issues/27

    I noticed some false positives when using transform in other namespaces. There may be some new false negatives when using namespace std is used and std:: is omitted, but it seems worth it.

    opened by geoffviola 0
  • using readability/fn_size with configurable parameter of lines

    using readability/fn_size with configurable parameter of lines

    Hi, I would like to set the maximal fn_size to 100 in my project and I already added a filter for readability/fn_size, but I couldn't find how exactly it can configure the number of lines, is it supported or should I change the code manually?

    opened by michael-novitsky 0
  • Add support for NOLINTBEGIN/END

    Add support for NOLINTBEGIN/END

    Add support for specifying no lint on multiple lines using a NOLINTBEGIN comment to start the block and one or more NOLINTEND comments. Multiple NOLINTBEGIN comments can stack different categories and the same number NOLINTEND comments need to be used to re-enable the category.

    This is similar to the clang-tidy NOLINTBEGIN/END feature.

    Also, add support for specifying multiple categories in a single NOLINT comment using commas as separators.

    https://github.com/google/styleguide/issues/31 https://github.com/cpplint/cpplint/issues/137

    opened by n3world 0
  • C++20 `[[likely]]` / `[[unlikely]]` attribute support

    C++20 `[[likely]]` / `[[unlikely]]` attribute support

    In C++ attribute: likely, unlikely (since C++20), we can add [[likely]] / [[unlikely]] on if-else clauses. But cpplint does not recognize the [[likely]] / [[unlikely]] attributes after if / else / else if:

    Source file:

    // foo.cpp
    // Copyright 2022 <test>
    
    #include <iostream>
    
    int fib1(int n) {
        if (n > 1) [[likely]] {
            int a;
            return fib1(n - 1) + fib1(n - 2);
        } else if (n == 2) [[unlikely]] {
            int b;
            return 1;
        } else [[unlikely]] {
            if (n == 1) [[likely]]
                return 1;
            else [[unlikely]]
                return 0;
        }
    }
    
    int fib2(int n) {
        switch (n) {
            [[unlikely]] case 0: return 0;
            case 1:
                [[fallthrough]];
            case 2:
                [[fallthrough]];
            [[unlikely]] case 3: {
                return 1;
            }
            [[likely]] default:
                return fib2(n - 1) + fib2(n - 2);
        }
    }
    

    Command-line:

    $ pip3 install -I git+https://github.com/cpplint/cpplint.git
    Looking in indexes: https://pypi.tuna.tsinghua.edu.cn/simple
    Collecting git+https://github.com/cpplint/cpplint.git
      Cloning https://github.com/cpplint/cpplint.git to /tmp/pip-req-build-6nkph3fd
      Running command git clone --filter=blob:none --quiet https://github.com/cpplint/cpplint.git /tmp/pip-req-build-6nkph3fd
      Resolved https://github.com/cpplint/cpplint.git to commit fa12a0bbdafa15291276ddd2a2dcd2ac7a2ce4cb
      Preparing metadata (setup.py) ... done
    Building wheels for collected packages: cpplint
      Building wheel for cpplint (setup.py) ... done
      Created wheel for cpplint: filename=cpplint-1.6.1-py3-none-any.whl size=77266 sha256=3e95bbfd3de2b8d61d561339213e6a4ae741e8bb110b34c9b6f626c55cd325c9
      Stored in directory: /tmp/pip-ephem-wheel-cache-d42ge4uo/wheels/af/90/88/663d23197700a259f2a9199aef67ee9977e21f6d1980257857
    Successfully built cpplint
    Installing collected packages: cpplint
    Successfully installed cpplint-1.6.1
    
    $ cpplint foo.cpp
    foo.cpp:7:  If/else bodies with multiple statements require braces  [readability/braces] [4]
    foo.cpp:10:  If/else bodies with multiple statements require braces  [readability/braces] [4]
    foo.cpp:13:  Else clause should never be on same line as else (use 2 lines)  [whitespace/newline] [4]
    foo.cpp:13:  If/else bodies with multiple statements require braces  [readability/braces] [4]
    foo.cpp:16:  Else clause should never be on same line as else (use 2 lines)  [whitespace/newline] [4]
    Done processing foo.cpp
    Total errors found: 5
    
    opened by XuehaiPan 0
  • #include <span> recognized as C system header

    #include recognized as C system header

    I have the following set of includes in my header file:

    #include <algorithm>
    #include <iostream>
    #include <span>
    #include <vector>
    

    If I leave them in this order, then I get the following error message:

    Found C system header after C++ system header. Should be: stream_helpers.h, c system, c++ system, other. [build/include_order] [4]

    In order to make the linter happy, I need to do this:

    #include <span>
    // ^^ Linter things <span> is a C system header :(
    #include <algorithm>
    #include <iostream>
    #include <vector>
    

    If I don't include the // comment below the #include <span> line, then my clang-format rule reorders the headers alphabetically but then cpplint fails.

    How do I go about fixing this?

    opened by michael-projectx 3
Owner
null
Qt-oriented static code analyzer based on the Clang framework

WARNING: master is the development branch. Please use the v1.10 branch. clazy v1.11 clazy is a compiler plugin which allows clang to understand Qt sem

KDE GitHub Mirror 555 Jan 8, 2023
Static analysis of C/C++ code

Cppcheck GitHub Actions Linux Build Status Windows Build Status OSS-Fuzz Coverity Scan Build Status License About the name The original name of this p

Daniel Marjamäki 4.5k Dec 30, 2022
A static analyzer for Java, C, C++, and Objective-C

Infer Infer is a static analysis tool for Java, C++, Objective-C, and C. Infer is written in OCaml. Installation Read our Getting Started page for det

Facebook 13.8k Jan 4, 2023
Static analyzer for C/C++ based on the theory of Abstract Interpretation.

IKOS IKOS (Inference Kernel for Open Static Analyzers) is a static analyzer for C/C++ based on the theory of Abstract Interpretation. Introduction IKO

NASA - Software V&V 1.8k Jan 4, 2023
Pharos Static Binary Analysis Framework

Automated static analysis tools for binary programs

Software Engineering Institute 1.3k Dec 18, 2022
ELF static analysis and injection framework that parse, manipulate and camouflage ELF files.

elfspirit elfspirit is a useful program that parse, manipulate and camouflage ELF files. It provides a variety of functions, including adding or delet

null 21 Dec 21, 2022
A static analysis tool that helps security researchers scan a list of Windows kernel drivers for common vulnerability patterns in drivers (CVE makers!)

Driver Analyzer A static analysis tool that helps security researchers scan a list of Windows kernel drivers for common vulnerability patterns in driv

BehroozAbbassi 44 Sep 3, 2022
Static analyzer for C/C++ based on the theory of Abstract Interpretation.

IKOS IKOS (Inference Kernel for Open Static Analyzers) is a static analyzer for C/C++ based on the theory of Abstract Interpretation. Introduction IKO

NASA - Software V&V 1.8k Dec 28, 2022
将 C/C++ 代码转换成流程图 / Turn your C/C++ code into flowchart

将 C/C++ 代码转换成流程图 / Turn your C/C++ code into flowchart

mgt 428 Jan 1, 2023
Static code checker for C++

cpplint - static code checker for C++ Cpplint is a command-line tool to check C/C++ files for style issues following Google's C++ style guide. Cpplint

null 1.2k Jan 7, 2023
IDA Pro key checker tool

IDA Key Checker IDA Pro (6.x-7.x) key checker tool Usage A list of available options can be retrieved using: ida_key_checker --help Arguments: Option

null 58 Dec 26, 2022
A model checker for the Dynamic Logic of Propositional Assignments (DL-PA) with solving and parameterized random formula generation functionalities.

A model checker for the Dynamic Logic of Propositional Assignments (DL-PA) with solving and parameterized random formula generation functionalities.

Jeffrey Yang 7 Dec 31, 2021
CITL's static analysis engine for native code artifacts

citl-static-analyzer Fast binary hardening analysis tooling. Building on Linux The build process varies by Linux distribution, owing to differences be

Cyber Independent Testing Lab 18 Aug 30, 2022
Qt-oriented static code analyzer based on the Clang framework

WARNING: master is the development branch. Please use the v1.10 branch. clazy v1.11 clazy is a compiler plugin which allows clang to understand Qt sem

KDE GitHub Mirror 555 Jan 8, 2023
Static analysis of C/C++ code

Cppcheck GitHub Actions Linux Build Status Windows Build Status OSS-Fuzz Coverity Scan Build Status License About the name The original name of this p

Daniel Marjamäki 4.5k Dec 30, 2022
Header-only, event based, tiny and easy to use libuv wrapper in modern C++ - now available as also shared/static library!

Do you have a question that doesn't require you to open an issue? Join the gitter channel. If you use uvw and you want to say thanks or support the pr

Michele Caini 1.5k Jan 1, 2023
A C++ static library offering a clean and simple interface to the 7-zip DLLs.

bit7z A C++ static library offering a clean and simple interface to the 7-zip DLLs Supported Features • Getting Started • Download • Requirements • Bu

Riccardo 326 Jan 1, 2023
A static analyzer for Java, C, C++, and Objective-C

Infer Infer is a static analysis tool for Java, C++, Objective-C, and C. Infer is written in OCaml. Installation Read our Getting Started page for det

Facebook 13.8k Jan 4, 2023