GithubHelp home page GithubHelp logo

cpplint's Introduction

cpplint - static code checker for C++

Cpplint is a command-line tool to check C/C++ files for style issues according to Google's C++ style guide.

Cpplint used to be developed and maintained by Google Inc. at google/styleguide. Nowadays, Google is no longer maintaining the public version of cpplint, and pretty much everything in their repo's PRs and issues about cpplint have gone unimplemented.

This fork aims to update cpplint to modern specifications, and be (somewhat) more open to adding fixes and features to make cpplint usable in wider contexts.

Installation

To install cpplint from PyPI, run:

$ pip install cpplint

Externally managed environments

If you get the "This environment is externally managed" error, try to search and install cpplint with your system's package manager (e.g. apt, rpm, pacman...). If it doesn't exist, you can either package cpplint for your distribution or repeat the steps above with the --break-system-packages flag.

Usage

$ cpplint [OPTIONS] files

For full usage instructions, run:

$ cpplint --help

Changes

  • python 3 compatibility
  • more default file extensions
  • customizable file extensions with the --extensions argument
  • continuous integration on github
  • 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 quite a bit more

Acknowledgements

Thanks to Google Inc. for open-sourcing their in-house tool.

Thanks to our contributors.

Maintainers

Former

cpplint's People

Contributors

aaronliu0130 avatar cclauss avatar cushon avatar danakj avatar eglaysher avatar elharo avatar gaal avatar geoffromer avatar geoffviola avatar gpshead avatar iam avatar isaacg avatar jameslamb avatar jayvdb avatar jbcoe avatar lhchavez avatar lukecz avatar markmentovai avatar mattyclarkson avatar norab0130 avatar piotr-semenov avatar pwnall avatar sfreilich avatar shicks avatar stephanemoore avatar theandrewdavis avatar tituswinters avatar tkruse avatar tonyruscoe avatar zetafunction avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

cpplint's Issues

Spyware

Your website is being black-listed as spyware by Barracuda Web Security Gateway:

The link you are accessing has been blocked by the Barracuda Web Security Gateway because it
contains spyware. The name of the spyware is: Spyware.Exploit.BRTS.cppstyle.com 

Any ideas why?

Looking for maintainers

I personally have moved into working with TypeScript and Rust so no longer daily work on C++. I still have an interest in the project as I feel that cpplint provides a great service to the C++ toolchain that is easily available in other languages.

If there are other people that use cpplint daily and are interested in moving the project forward get in touch on this issue.

Consider inclusion of open PRs on Upstream

Manually gathering PRs that might be good (or not):

Python3 support

Indentation:

  • google#401 (override the access modifier indentation)
  • google#192 (Override indent spaces) closed in upstream?
  • google#190 (Improved indent testing and Override indent spaces)

New features:

  • google#374 (Add structured binding support from c++17 to cpplint)
  • google#366 (Enables includes with relative paths)
  • google#312 (add "return" to the compound literal exclusions)
  • google#218 (Add the tokens signed and unsigned to the definition of a type)
  • google#281 (C++ 17 string_view support)
  • google#216 (Fix false positive alarms on missed or header.)
  • google#108 (Don't replace - with _ in header names prior to sorting.)
  • google#175 (Extended CStyleCast regular expressions) Close in upstream without explanation
  • google#166 (Allow space before C++11 attributes)
  • google#134 (Changed stream from stderr to stdout for successful processing) already done?
  • google#346 (fix --root on windows)

Rejected

In any case I added a comment pointing contributors to this fork.

cpplint license "Freely Distributable"

The cpplint setup.py uses classifier "Freely Distributable", but provides no license.

As a result the distributed pacakge info is:

PKG-INFO:License: UNKNOWN

cpplint should use an SPDX compatible license.

Skip C++-specific warnings for C code

For source code files with .[cChH] extension, please skip warnings meant for C++ code, so that programmers don't accidentally introduce C++-isms into their C code.

Example: readability/casting and runtime/int should be disabled for C code.

As a workaround, I am disabling these rules regardless of the source language, so that I can run cpplint more reliably across my C, C++, and mixed C/C++ projects.

ignore line

Are any possibility to ignore checking line in code, like in eslint or jshint:

some code \\ ccplint-ignore-line [... rules]

spurious "should include its header file"

If "Foo.h" exist and you have a file like this name Foo.cc

#include "Foo.h"

There is an error like this:

 ... Foo.cc should include its header file src/Foo.h  [build/include] [5]

This is because "Foo.h" is excluded from the include_state since it matches _THIRD_PARTY_HEADERS_PATTERN
In this case it should not be excluded because we are checking "Foo.cc".

gunzip fix-spurious-should-include-its-header-file.patch.gz
git apply fix-spurious-should-include-its-header-file.patch

fix-spurious-should-include-its-header-file.patch.gz

patch tested with 1e7ecd3

Add --quiet option

It would be helpful if a --quiet option were added to cpplint so that the user could control if they just want to see the error output (useful if you run cpplint on a large number of files at once).

I'm undecided if the Total errors found: _ should stay when in --quiet, but I am leaning towards yes.

Enhancement: Recurse on directories

cpplint currently requires source code file paths to be explicitly, individually declared. This makes it harder to use cpplint across large codebases.

As a workaround, some users can invoke findutils to identify all C and C++ source files, piping the results to cpplint within xargs. However, this is error prone and macOS doesn't support the same options for xargs as most other UNIX systems. Additionally, findutils is not available out of the box for Windows, so users must then either install findutils in a cygwin-like environment (which brings its own problems), or write MS DOS batch scripts / PowerShell scripts to scan for C, C++ files and invoke cpplint on them one by one. This is painful.

In the future, could cpplint just accept a directory path like src, lib, etc., and recurse over that?

False positive: Add #include <algorithm> for sort

Cpplint seems to assume that all standard algorithms come from the STL,
so, for example, if Boost algorithms are used,
the linter suggests to include <algorithm>.
Note that the function call is fully qualified as is required by the Google style:

#include <boost/range/algorithm.hpp>

void foo() {
  boost::sort(std::vector<int>{1, 2, 3, 4});
}

The solution strategy could be to take into account std:: qualification for function calls.

Feature request: Discourage assert()

Modern C/C++ programming prefers perror() or returning error values, to using assert(). I understand this is because assert() often becomes a NOP in release binaries, and assert() can occasionally leak sensitive information.

Given that assert() is now frowned upon, could cpplint update its rule checks to recommend suitable replacements in our source code files?

RValue reference not guessed correctly when on new line

To reproduce:

struct A {};
void create_output(const char *c,
                   A&& a);

As reported here: google#61
Related to #24

Hint to bugfix: In order to classify A&& a correctly, with the current strategy, cpplint would have to extend it's search for a function opener over the previous lines, around the spot where #24 made fixes. It's feasible, but will add to the mess inside cpplint.

Disambiguate header guards

To reproduce, create headers:

include/foo/baz_bar.h
include/foo_baz/bar.h

having distinct header guards

See google#78

No ideal solution provided so far.

Issue with 16 bit representation of unicode characters

To reproduce:

#!/bin/bash

set -exuo pipefail

PYTHON_TAG_TO_CHECK=v2.7.4
PYTHON_UCS2="${PWD}/cpython/python_v2.7.10_ucs2"
PYTHON_UCS4="${PWD}/cpython/python_v2.7.10_ucs4"
NJOBS=16

git clone https://github.com/python/cpython.git
cd cpython
git checkout $PYTHON_TAG_TO_CHECK


mkdir ${PYTHON_UCS2}
mkdir ${PYTHON_UCS4}


test_with_cpp_lint() {
	local CMD="${1}/bin/python2.7 cpplint.py --filter=-build/header_guard,-legal/copyright initial_value_problem.h 2>&1"
	local output="$(eval ${CMD})"
	echo "${output}"
}

test_unicode_size() {
	if [ $(cat pyconfig.h | grep -cE "^\#define Py_UNICODE_SIZE $1$") -ne 1 ]; then
		echo "Py_UNICODE_SIZE ASSERTION FAILED"
		exit 1
			fi
}

check_assertion(){
    if [[ "$OUTPUT" != "$EXPECTED_OUTPUT" ]]; then
        echo "OUTPUT ASSERTION FAILED"
        exit
    fi
}


wget https://raw.githubusercontent.com/google/styleguide/gh-pages/cpplint/cpplint.py

# The motivation of the excercise (Line 18)
wget https://raw.githubusercontent.com/RobotLocomotion/drake/b6ff34893b83430c79043d0b6c29e00b8c04de52/systems/analysis/initial_value_problem.h

# The default is ucs2
# https://github.com/python/cpython/blob/1ce4e5bee6df476836f799456f2caf77cd13dc97/configure#L1473
./configure --prefix="${PYTHON_UCS2}" && make -j$NJOBS && make install
test_unicode_size 2

OUTPUT="$(test_with_cpp_lint $PYTHON_UCS2)"
EXPECTED_OUTPUT="$(cat << ENDOFTEXT
initial_value_problem.h:18:  Lines should be <= 80 characters long  [whitespace/line_length] [2]
initial_value_problem.h:19:  Lines should be <= 80 characters long  [whitespace/line_length] [2]
Done processing initial_value_problem.h
Total errors found: 2
ENDOFTEXT
)"
check_assertion

# Checking with --enable-unicode=ucs4
./configure --prefix="${PYTHON_UCS4}" --enable-unicode=ucs4 && make -j$NJOBS && make install
test_unicode_size 4

OUTPUT="$(test_with_cpp_lint $PYTHON_UCS4)"
EXPECTED_OUTPUT="$(cat << ENDOFTEXT
Done processing initial_value_problem.h
Total errors found: 0
ENDOFTEXT
)"
check_assertion

exit 0

Naming .h includes without dir

The script seems to be assuming that all header files are located in a subdirectory under src/
and produces "Include directory when naming .h files" for includes within quotes, project header files.
The snippet from the GCSG:

All of a project's header files should be listed as descendants of the project's source directory without use of UNIX directory shortcuts

However, some or all headers may be located in src itself, so the includes do not need
appending any directory in naming.

cpplint output error when it is a git submodule

cpplint checks a project and prints no error found.
When the same project is as a git submodule, cpplint prints multiple errors.

include/base_code.hpp:6:  #ifndef header guard has wrong style, please use: COMPANY_COMMON_INCLUDE_BASE_CODE_HPP_  [build/header_guard] [5]
include/base_code.hpp:56:  #endif line should be "#endif  // COMPANY_COMMON_INCLUDE_BASE_CODE_HPP_"  [build/header_guard] [5]

Should this project contain/support a GitHub Action for cpplint?

Should this project contain the code for a simple yet flexible GitHub Action that allows repo maintainers to quickly add automated cpplint testing on all pull requests submitted to their repos?

Putting that code into this repo or another cpplint org repo will focus development efforts on a single, community supported GitHub Action for cpplint instead of a multitude of homegrown solutions.

Currently you must be in the GitHub Action beta to be able to use Actions.

https://github.com/cclauss/GitHub-Action-for-cpplint

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.')

Non-explicit copy construtors

CPPLint warns about non-explicit copy constructors which makes no sense as implicitly generated copy constructors are non-explicit as well (https://en.cppreference.com/w/cpp/language/copy_constructor#Implicitly-declared_copy_constructor).

Example:

struct Foo {
  /// Copy constructor.
  Foo(const Foo & other)
  : member(other.member) {}
  int member;
}

yields:

- containers.cpplint runtime/explicit [5]
  <<< failure message
    Single-parameter constructors should be marked explicit.
  >>>

Is there a way to configure this behavior?

Specify unapproved C++11 and C++14 features

The tuples that contain unapproved C++11 and C++14 can be made to be customisable through --cxx11-unapproved-headers=thread, [--cxx11-unapproved-classes=](https://github.com/theandrewdavis/cpplint/blob/a33992f68f36fcaa6d0f531a25012a4c474d3542/cpplint.py#L6023-L6027) (could have a --cxx11-unapproved-functions=` that is merged or split out). Same for C++14. Would this be something that would be acceptable for a PR?

Order of includes error for 3rd party libraries (reopened)

(reopening issue #7 because it was closed without resolution)
The following example snippet produces "Found C system header after C++ system header...[build/include_order]".

#include <vector>

#include <gtest/gtest.h>

The problem goes away if the angle brackets are replaced by quotes.
I guess the script assumes the angle brackets only for C/C++ system and standard library headers.

I think the CORRECT behavior would be to encode into cpplint the full list of C system and standard-library headers (as is done with C++ standard headers).

Here's a suggested starting place:

  • The system C headers (per https://en.cppreference.com/w/c/header):
    • assert.h
    • complex.h
    • ctype.h
    • errno.h
    • fenv.h
    • float.h
    • inttypes.h
    • iso646.h
    • limits.h
    • locale.h
    • math.h
    • setjmp.h
    • signal.h
    • stdalign.h
    • stdarg.h
    • stdatomic.h
    • stdbool.h
    • stddef.h
    • stdint.h
    • stdio.h
    • stdlib.h
    • stdnoreturn.h
    • string.h
    • tgmath.h
    • threads.h
    • time.h
    • uchar.h
    • wchar.h
    • wctype.h
  • POSIX C headers (per http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/contents.html)
    • aio.h
    • arpa/inet.h
    • cpio.h
    • dirent.h
    • dlfcn.h
    • fcntl.h
    • fmtmsg.h
    • fnmatch.h
    • ftw.h
    • glob.h
    • grp.h
    • iconv.h
    • langinfo.h
    • libgen.h
    • monetary.h
    • mqueue.h
    • ndbm.h
    • net/if.h
    • netdb.h
    • netinet/in.h
    • netinet/tcp.h
    • nl_types.h
    • poll.h
    • pthread.h
    • pwd.h
    • regex.h
    • sched.h
    • search.h
    • semaphore.h
    • setjmp.h
    • signal.h
    • spawn.h
    • strings.h
    • stropts.h
    • syslog.h
    • tar.h
    • termios.h
    • trace.h
    • ulimit.h
    • unistd.h
    • utime.h
    • utmpx.h
    • wordexp.h
  • GNUlib Headers
    • a.out.h
    • aliases.h
    • alloca.h
    • ar.h
    • argp.h
    • argz.h
    • byteswap.h
    • crypt.h
    • endian.h
    • envz.h
    • err.h
    • error.h
    • execinfo.h
    • fpu_control.h
    • fstab.h
    • fts.h
    • getopt.h
    • gshadow.h
    • ieee754.h
    • ifaddrs.h
    • libintl.h
    • mcheck.h
    • mntent.h
    • obstack.h
    • paths.h
    • printf.h
    • pty.h
    • resolv.h
    • shadow.h
    • sysexits.h
    • ttyent.h
  • Other system-specific C headers
    • sys/*.h
  • Hardware-specific C system headers
    • arm_neon.h
    • emmintrin.h
    • xmmintrin.h

Order of includes error for 3rd party libraries

The following example snippet produces "Found C system header after C++ system header...[build/include_order]".

#include <vector>

#include <boost/any.hpp>

The problem goes away if the angle brackets are replaced by quotes.
I guess the script assumes the angle brackets only for C/C++ system and standard library headers.

Allow module usage

Due to global variables it is not possible to do something like:

import cpplint
cpplint.ProcessFile(filepathOne)
cpplint.ProcessFile(filepathTwo)

This would require refactoring all the global state into the CpplintState class and passing it between functions.

Would this be something that would be of interest to the project? We would like to use cpplint in our Python build tool and using it at a module would simplify things hugely.

Exclude ignores wildcard on folder names

I'm trying to use cpplint to check some Arduino code. I'm using --recursive to find all source files in numerous sub-directories. However, this is causing it to pick up the auto-generated code that the Arduino preprocessor creates in .build directories.

Per the --help documentation, I believe I should be able to direct the tool to ignore these folders with a call like:

cpplint --recursive --exclude=.build src

However, this does not work, and cpplint still attempts to parse the auto-generated (and messy) Arduino code. I've also tried:

cpplint --recursive --exclude=*/.build src

as well as other wildcard variations, but nothing seems to work.

The docs say --exclude supports globbing, but if that were so, I would expect one of these patterns to work. Am I misunderstanding it, or is this a limitation of cpplint?

Merge upstream/gh-pages branch to master

Fetching upstream changes should be made easy, for that we regularly need to merge upstream gh-pages branch into our master branch. We should do this as a no-op merge once this list of PRs has been merged:

  • #52
  • #51
  • #53 (after rebase and tests pass)
  • #53 (after rebase and tests pass)
  • #55 (after rebase and tests pass)
  • #56 (after rebase and tests pass)
  • #57 (after rebase and tests pass)
  • #58 (after rebase and tests pass)

Stream arguments passed by reference

Non-const reference arguments for functions are violation of the guideline.
For output arguments, the pointers are requested,
but passing streams with pointers is awkward.

void Print(std::ostream* out) { (*out) << "text"; }
Print(&std::cout);

vs.

void Print(std::ostream& out) { out << "text"; }
Print(std::cout);

Cpplint only excuses streams by reference on overloading the operator<<.
It would also be helpful to completely exclude streams from the rule of pass variable only by const reference.

Custom namespace triggers false positive error for parameters passed by rvalue reference

Consider the following code in test.cpp:

// Copyright [year] <Copyright Owner>

namespace name {
    using Color = int;
}

class Class {
    void method(name::Color&& val);
};

void Class::method(name::Color&& val) {
    return;
}
$ pip list
...
cpplint (1.2.1)
$ cpplint --filter=-build/c++11 test.cpp
test.cpp:8:  Missing spaces around &&  [whitespace/operators] [3]
test.cpp:11:  Missing spaces around &&  [whitespace/operators] [3]
Done processing test.cpp
Total errors found: 2

If you remove the custom namespace name:: from the parameter types, cpplint does not throw errors, so that seems to be tripping up the analysis.

Preprocessor directives are seen as functions

The preprocessor directive #elif (<expression>) is seen as a function call and so the error [whitespace/parens] is raised.

Example: https://pastebin.com/VC7q0Gz1

The problem is not raised with #if (<expression>), probably because it detects if as a control structure and is ignored. A possible hack can be applied by adding elif to the ignored control structures (see patch https://pastebin.com/ZgBBG3Wf) in CheckSpacingForFunctionCall.

Though, it would be better to ignore preprocessor directives.

Header guard warning when using pragma once.

I'm working in a codebase that occasionally uses #pragma once instead of a standard include guard. cpplint doesn't like this though and complains about a lack of include guard when there effectively is one. How do I get around this?

Header guard handling conflicts with Google spec

According to the [Google guidelines](https://google.github.io/styleguide/cppguide. html#The__define_Guard), the format of the header guard is:
{PROJECT}_{FILEPATH}_{FILENAME}_
e.g. HELLOWORLD_SRC_INCLUDE_HEADER_H_

However, CppLint.py insists that the header guard format must be: {FILEPATH}_{FILENAME}_

We need a way to specify the $PROJECT

Also, the Google spec specifies that the header guard is an exception to the line-length limits, but cpplint.py does not treat it as an exception.

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.

Allow #endif /* GUARD */ style header guards

When checking C89 headers the header guard must use the /* */ style comments so the warning should allow that.

include/vca/test/macros.h:216:  #endif line should be "#endif  // INCLUDE_VCA_TEST_MACROS_H_"  [build/header_guard] [5]

I know that this is cpplint but I think it should still allow headers that are C89 compatible in a C++ project.

Suggestion on readability/naming

There are 2 cases I've met, which I think should be false-positive during error checking:

case 1:
std::placeholders::_1

This always causes lint error, saying that _ as prefix should only be used in system reserved sdk, while we don't have the rights to change the variable definition in STL, though.

case 2:
#define func(arg) prefix_##arg##_suffix

The _suffix results in the same lint error, while in fact this is just part of a macro, and there make no variable or function with _ as prefix actually, for '##' stands for code concat.

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.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.