Used but never defined error

In a .h file, I have:inline _C3DTVector vectorInterpolate(const _C3DTVector a, const _C3DTVector b, const float interpolation);and in a .c file: inline _C3DTVector vectorInterpolate(const _C3DTVector a, const _C3DTVector b, const float interpolation) { _C3DTVector r; r.x =...

Catfish

Ars Tribunus Angusticlavius


  • Add bookmark

  • #1

In a .h file, I have:<BR><pre class=»ip-ubbcode-code-pre»>inline _C3DTVector vectorInterpolate(const _C3DTVector a, const _C3DTVector b, const float interpolation);</pre><BR><BR>and in a .c file:<BR><pre class=»ip-ubbcode-code-pre»>
inline _C3DTVector vectorInterpolate(const _C3DTVector a, const _C3DTVector b, const float interpolation)
{
_C3DTVector r;

r.x = a.x*interpolation + b.x*(1-interpolation);
r.y = a.y*interpolation + b.y*(1-interpolation);
r.z = a.z*interpolation + b.z*(1-interpolation);

return r;
}
</pre><BR><BR><BR>Can anyone tell me why I get a warning on compiling?<BR><BR><pre class=»ip-ubbcode-code-pre»>/Users/jon/Developer/AlbumCocoaBrowser/C3DTMath.h:113: warning: inline function `_C3DTVector vectorInterpolate(_C3DTVector, _C3DTVector, float)’ used but never defined</pre><BR><BR><BR><BR>The function works perfectly at runtime. What the hell is the compiler going on about?

  • Add bookmark

  • #2

You’re supposed to put the inline function’s definition in the header file. Otherwise the compiler doesn’t know what to insert into the call-sites when it’s compiling other source files.<BR><BR>From the C++ FAQ:<BR>How do you tell the compiler to make a non-member function inline?<BR><BR><BLOCKQUOTE class=»ip-ubbcode-quote»><div class=»ip-ubbcode-quote-title»>quote:</div><div class=»ip-ubbcode-quote-content»>The function works perfectly at runtime. </div></BLOCKQUOTE>Probably because it defaulted back to a standard, non-inlined function call.

Catfish

Ars Tribunus Angusticlavius


  • Add bookmark

  • #3

Hmm. OK, done.<BR><BR>One question — was this the case in plain C, too? Because I’ve got a C project here that uses the inline functions in .h & .c files and it doesn’t complain…

  • Add bookmark

  • #4

C89 doesn’t have a notion of inline functions.<BR><BR>C99 does, and from my interpretation of the standard, it should behave the same way. (How would the compiler work otherwise?)

  • Add bookmark

  • #5

<BLOCKQUOTE class=»ip-ubbcode-quote»><div class=»ip-ubbcode-quote-title»>quote:</div><div class=»ip-ubbcode-quote-content»>Originally posted by stickboy:<BR>Probably because it defaulted back to a standard, non-inlined function call. </div></BLOCKQUOTE><BR><BR>Yeah, I think this is the case too. gcc is probably treating your H file function definition like a regular function *prototype*, as it finds the implementation in your C file.

History

This warning has existed in two forms in JSLint, JSHint and ESLint. It was
introduced in the original version of JSLint and has remained in all three
linters ever since.

  • In JSLint the warning given is «Unused ‘{a}'»

  • In JSHint and ESLint the message has always been «‘{a}’ is defined but never
    used»

When do I get this error?

The «Unused ‘{a}'» error, and the alternative «‘{a}’ is defined but never used»,
is thrown when JSLint, JSHint or ESLint encounters an environment record
binding with an identifier that is not referenced aside from its declaration
.
In JSHint the warning is only raised if the unused option is set to true. In
the following example there are various unused identifiers:

/*jshint unused: true */
function demo(a, b) {
    "use strict";
    var c;
}

Why do I get this error?

This error is raised to highlight a potentially useless code. Your code will
run without error if you just ignore this warning, but it could be doing
unnecessary work and could be confusing to other developers exposed to your
code.

When you declare a variable or a function in JavaScript there is no obligation
to use it later on. Therefore, code such as the example above is perfectly valid
but also completely useless. If this warning relates to variables that are
simply defined and never used, you can simply remove those variable declarations
completely. However, sometimes you may declare variables in one file but use
them in another. If that’s the case and you’re using JSHint you can use the
exported directive to signify those variables:

/*jshint unused: true */
/*exported demo */
function demo(a, b) {
    "use strict";
    var c;
}

A note about function arguments

The behaviour described above is not ideal when it comes to function parameters.
It’s relatively common to have function arguments that are not referred to
within the function but are necessary in the function signature because
subsequent arguments are referred to. For example:

/*jshint unused: true, node: true */
/*jslint node: true */
var fs = require("fs");
fs.readdir("dir", function (err, files) {
    "use strict";
    console.log(files); // Ignoring any error in 'err'
});

In this example we don’t care about the err argument so we don’t refer to it.
JSLint still complains that the variable is unused. JSHint and ESLint are clever
enough to know that since files is used there is no need to warn about err
but in JSLint you’ll have to set the unparam option to true to avoid a
warning in this situation:

/*jshint unused: true, node: true */
/*jslint unparam: true, node: true */
var fs = require("fs");
fs.readdir("dir", function (err, files) {
    "use strict";
    console.log(files); // Ignoring any error in 'err'
});

In JSHint 1.1.0 and above you are able to configure the behaviour around
function arguments. The unused option accepts a string rather than a boolean:

  • vars — Only warn about unused variable and function declarations. Don’t
    warn about any function parameters.

  • last-param — Warn about unused variable and function declarations and the
    last parameter of functions. This is the default value if you set the option
    to true.

  • strict — Warn about unused variable and function declarations and all
    parameters of functions. This is the equivalent to the pre-1.1.0 and JSLint
    behaviour.

In JSHint 1.0.0 and above you have the ability to ignore any warning with a
special option syntax. The identifier of this warning is W098.
This means you can tell JSHint to not issue this warning with the /*jshint
-W098 */
directive.

In ESLint the rule that generates this warning is named no-unused-vars. You
can disable it by setting it to 0, or enable it by setting it to 1.

Содержание

  1. no-unused-vars
  2. Rule Details
  3. exported
  4. Options
  5. vars: local
  6. varsIgnorePattern
  7. args: after-used
  8. args: all
  9. args: none
  10. argsIgnorePattern
  11. caughtErrors
  12. caughtErrors: none
  13. caughtErrors: all
  14. caughtErrorsIgnorePattern
  15. destructuredArrayIgnorePattern
  16. ignoreRestSiblings
  17. When Not To Use It
  18. ‘React’ is defined but never used no-unused-vars #11183
  19. Comments
  20. no-unused-vars
  21. Как отключить правило ESLint?
  22. Как обойти ESLint?
  23. Как запустить автоисправление ESLint?
  24. Как автоматически удалять неиспользуемый импорт?
  25. Как избавиться от неиспользуемого импорта?
  26. Как удалить все неиспользуемые импорты в react?
  27. Как отключить Vscode ESLint?
  28. Rule Details
  29. exported
  30. Options
  31. vars: local
  32. varsIgnorePattern
  33. args: after-used
  34. args: all
  35. args: none
  36. ignoreRestSiblings
  37. argsIgnorePattern
  38. destructuredArrayIgnorePattern
  39. caughtErrors
  40. caughtErrors: none
  41. caughtErrors: all
  42. caughtErrorsIgnorePattern
  43. Когда не использовать его

no-unused-vars

Disallow unused variables

The «extends»: «eslint:recommended» property in a configuration file enables this rule

Variables that are declared and not used anywhere in the code are most likely an error due to incomplete refactoring. Such variables take up space in the code and can lead to confusion by readers.

Rule Details

This rule is aimed at eliminating unused variables, functions, and function parameters.

A variable foo is considered to be used if any of the following are true:

  • It is called ( foo() ) or constructed ( new foo() )
  • It is read ( var bar = foo )
  • It is passed into a function as an argument ( doSomething(foo) )
  • It is read inside of a function that is passed to another function ( doSomething(function() < foo(); >) )

A variable is not considered to be used if it is only ever declared ( var foo = 5 ) or assigned to ( foo = 7 ).

Examples of incorrect code for this rule:

Examples of correct code for this rule:

exported

In environments outside of CommonJS or ECMAScript modules, you may use var to create a global variable that may be used by other scripts. You can use the /* exported variableName */ comment block to indicate that this variable is being exported and therefore should not be considered unused.

Note that /* exported */ has no effect for any of the following:

  • when the environment is node or commonjs
  • when parserOptions.sourceType is module
  • when ecmaFeatures.globalReturn is true

The line comment // exported variableName will not work as exported is not line-specific.

Examples of correct code for /* exported variableName */ operation:

Options

This rule takes one argument which can be a string or an object. The string settings are the same as those of the vars property (explained below).

By default this rule is enabled with all option for variables and after-used for arguments.

The vars option has two settings:

  • all checks all variables for usage, including those in the global scope. This is the default setting.
  • local checks only that locally-declared variables are used but will allow global variables to be unused.

vars: local

Examples of correct code for the < «vars»: «local» >option:

varsIgnorePattern

The varsIgnorePattern option specifies exceptions not to check for usage: variables whose names match a regexp pattern. For example, variables whose names contain ignored or Ignored .

Examples of correct code for the < «varsIgnorePattern»: «[iI]gnored» >option:

The args option has three settings:

  • after-used — unused positional arguments that occur before the last used argument will not be checked, but all named arguments and all positional arguments after the last used argument will be checked.
  • all — all named arguments must be used.
  • none — do not check arguments.

args: after-used

Examples of incorrect code for the default < «args»: «after-used» >option:

Examples of correct code for the default < «args»: «after-used» >option:

args: all

Examples of incorrect code for the < «args»: «all» >option:

args: none

Examples of correct code for the < «args»: «none» >option:

argsIgnorePattern

The argsIgnorePattern option specifies exceptions not to check for usage: arguments whose names match a regexp pattern. For example, variables whose names begin with an underscore.

Examples of correct code for the < «argsIgnorePattern»: «^_» >option:

caughtErrors

The caughtErrors option is used for catch block arguments validation.

It has two settings:

  • none — do not check error objects. This is the default setting.
  • all — all named arguments must be used.

caughtErrors: none

Not specifying this rule is equivalent of assigning it to none .

Examples of correct code for the < «caughtErrors»: «none» >option:

caughtErrors: all

Examples of incorrect code for the < «caughtErrors»: «all» >option:

caughtErrorsIgnorePattern

The caughtErrorsIgnorePattern option specifies exceptions not to check for usage: catch arguments whose names match a regexp pattern. For example, variables whose names begin with a string ‘ignore’.

Examples of correct code for the < «caughtErrorsIgnorePattern»: «^ignore» >option:

destructuredArrayIgnorePattern

The destructuredArrayIgnorePattern option specifies exceptions not to check for usage: elements of array destructuring patterns whose names match a regexp pattern. For example, variables whose names begin with an underscore.

Examples of correct code for the < «destructuredArrayIgnorePattern»: «^_» >option:

ignoreRestSiblings

The ignoreRestSiblings option is a boolean (default: false ). Using a Rest Property it is possible to “omit” properties from an object, but by default the sibling properties are marked as “unused”. With this option enabled the rest property’s siblings are ignored.

Examples of correct code for the < «ignoreRestSiblings»: true >option:

When Not To Use It

If you don’t want to be notified about unused variables or function arguments, you can safely turn this rule off.

Источник

‘React’ is defined but never used no-unused-vars #11183

When i run eslint on my code, I get the error:
‘React’ is defined but never used no-unused-vars
when I remove import ‘React’ from ‘react’ I get the error
‘React’ must be in scope when using JSX

I tried enabling the rules below but still receive the error.
«react/jsx-uses-react»: 1,
«react/jsx-uses-vars»: 1,
«react/react-in-jsx-scope»: 1

Can someone help me check if my configurations are correct, if I’m not overriding anything?

I am using these versions in package.json:
devDependencies

The text was updated successfully, but these errors were encountered:

Hi @VanessaChu, thanks for the issue.

Your configuration looks good to me. Would you mind trying to run ESLint with the —debug flag to see if another configuration is being picked up unexpectedly?

@VanessaChu I’m guessing that you are describing code that looks like this:

I think that the rules configuration might not work in this scenario. However, the rules you are working with are from a plugin called eslint-plugin-react , so I’m not really familiar with how they are supposed to work. I would suggest contacting the plugin authors: https://github.com/yannickcr/eslint-plugin-react/issues

You might need to enable the react/jsx-uses-react rule.

@platinumazure after running npm run lint —debug
Lifecycle scripts included:
test
jest

available via npm run-script :
build
npm run copy-src
copy-src
(cd build && mkdir -p lib/commonjs/story-builder) && cp -r src/* package.json build/lib/commonjs/story-builder
clean
cd build && rm -r lib/commonjs/story-builder
release
npm run lint && npm run build && npm run test
test-watch
jest —watch
test-debug
node —inspect-brk node_modules/.bin/jest —runInBand
lint
node node_modules/.bin/eslint src/ test/ —fix

@not-an-aardvark I have already enabled react/jsx-uses-react with «react/jsx-uses-react»: 1,

My apologies, I didn’t realize you were running an npm script. Adding just —debug to an npm script results in npm’s debug logs being visible, rather than ESLint’s.

Could you try running the script with — —debug on the end? This ensures the —debug parameter is passed to ESLint rather than consumed by npm. Thanks!

@VanessaChu Does your code contain valid JSX?

Unfortunately, it looks like there wasn’t enough interest from the team
or community to implement this change. While we wish we’d be able to
accommodate everyone’s requests, we do need to prioritize. We’ve found
that issues failing to reach accepted status after 21 days tend to
never be accepted, and as such, we close those issues.
This doesn’t mean the idea isn’t interesting or useful, just that it’s
not something the team can commit to.

Thanks for contributing to ESLint and we appreciate your understanding.

Источник

no-unused-vars

Запретить неиспользуемые переменные

Как отключить правило ESLint?

Как обойти ESLint?

Как запустить автоисправление ESLint?

Как автоматически удалять неиспользуемый импорт?

Как избавиться от неиспользуемого импорта?

Как удалить все неиспользуемые импорты в react?

Как отключить Vscode ESLint?

«extends»: «eslint:recommended» property in a configuration file enables this rule’ onmousemove=»i18n(this)»>Свойство «extends»: «eslint:recommended» в файле конфигурации включает это правило .

Переменные,которые объявлены и нигде не используются в коде,скорее всего,являются ошибкой из-за неполного рефакторинга.Такие переменные занимают место в коде и могут привести к путанице у читателей.

Rule Details

Данное правило направлено на устранение неиспользуемых переменных,функций и параметров функции.

foo is considered to be used if any of the following are true:» onmousemove=»i18n(this)»>Переменная foo считается использованной, если выполняется одно из следующих условий:

  • foo() ) or constructed ( new foo() )» onmousemove=»i18n(this)»>Он называется ( foo() ) или сконструирован ( new foo() )
  • var bar = foo )» onmousemove=»i18n(this)»>Читается ( var bar = foo )
  • doSomething(foo) )» onmousemove=»i18n(this)»>Он передается в функцию как аргумент ( doSomething(foo) )
  • doSomething(function() < foo(); >) )» onmousemove=»i18n(this)»>Он читается внутри функции, которая передается другой функции ( doSomething(function() < foo(); >) )

var foo = 5 ) or assigned to ( foo = 7 ).» onmousemove=»i18n(this)»>Переменная не считается использованной, если она только когда-либо была объявлена ​​( var foo = 5 ) или присвоена ( foo = 7 ).

Примеры неправильного кода для этого правила:

Примеры правильного кода для этого правила:

exported

var to create a global variable that may be used by other scripts. You can use the /* exported variableName */ comment block to indicate that this variable is being exported and therefore should not be considered unused.» onmousemove=»i18n(this)»>В средах за пределами модулей CommonJS или ECMAScript вы можете использовать var для создания глобальной переменной, которая может использоваться другими скриптами. Вы можете использовать блок комментариев /* exported variableName */ чтобы указать, что эта переменная экспортируется и, следовательно, не должна считаться неиспользованной.

/* exported */ has no effect for any of the following:» onmousemove=»i18n(this)»>Обратите внимание, что /* exported */ не влияет ни на одно из следующего:

  • node or commonjs » onmousemove=»i18n(this)»>когда среда является node или commonjs
  • parserOptions.sourceType is module » onmousemove=»i18n(this)»>когда parserOptions.sourceType является module
  • ecmaFeatures.globalReturn is true » onmousemove=»i18n(this)»>когда ecmaFeatures.globalReturn является true

// exported variableName will not work as exported is not line-specific.» onmousemove=»i18n(this)»>Комментарий к строке // exported variableName не будет работать, так как exported строка не зависит от конкретной строки.

/* exported variableName */ operation:» onmousemove=»i18n(this)»>Примеры правильного кода для операции /* exported variableName */ :

Options

vars property (explained below).» onmousemove=»i18n(this)»>Это правило принимает один аргумент, который может быть строкой или объектом. Настройки строки такие же, как у свойства vars (объяснено ниже).

all option for variables and after-used for arguments.» onmousemove=»i18n(this)»>По умолчанию это правило включено со all параметрами для переменных и after-used для аргументов.

vars option has two settings:» onmousemove=»i18n(this)»>Опция vars имеет две настройки:

  • all checks all variables for usage, including those in the global scope. This is the default setting.» onmousemove=»i18n(this)»> all проверяет все переменные на предмет использования, в том числе в глобальной области. Это значение по умолчанию.
  • local checks only that locally-declared variables are used but will allow global variables to be unused.» onmousemove=»i18n(this)»> local проверяет только то, что используются локально объявленные переменные, но допускает неиспользование глобальных переменных.

vars: local

< «vars»: «local» >option:’ onmousemove=»i18n(this)»>Примеры правильного кода для параметра < «vars»: «local» >:

varsIgnorePattern

varsIgnorePattern option specifies exceptions not to check for usage: variables whose names match a regexp pattern. For example, variables whose names contain ignored or Ignored .» onmousemove=»i18n(this)»>Параметр varsIgnorePattern указывает исключения, которые не следует проверять на использование: переменные, имена которых соответствуют шаблону регулярного выражения. Например, переменные, имена которых содержат ignored или Ignored .

< «varsIgnorePattern»: «[iI]gnored» >option:’ onmousemove=»i18n(this)»>Примеры правильного кода для параметра < «varsIgnorePattern»: «[iI]gnored» >:

args option has three settings:» onmousemove=»i18n(this)»>Параметр args имеет три настройки:

  • after-used — unused positional arguments that occur before the last used argument will not be checked, but all named arguments and all positional arguments after the last used argument will be checked.» onmousemove=»i18n(this)»> after-used — неиспользуемые позиционные аргументы, которые встречаются перед последним использованным аргументом, не будут проверяться, но будут проверены все именованные аргументы и все позиционные аргументы после последнего использованного аргумента.
  • all — all named arguments must be used.» onmousemove=»i18n(this)»> all — должны использоваться все именованные аргументы.
  • none — do not check arguments.» onmousemove=»i18n(this)»> none — не проверять аргументы.

args: after-used

< «args»: «after-used» >option:’ onmousemove=»i18n(this)»>Примеры неправильного кода для параметра по умолчанию < «args»: «after-used» >:

< «args»: «after-used» >option:’ onmousemove=»i18n(this)»>Примеры правильного кода для опции по умолчанию < «args»: «after-used» >:

args: all

< «args»: «all» >option:’ onmousemove=»i18n(this)»>Примеры неправильного кода для параметра < «args»: «all» >:

args: none

< «args»: «none» >option:’ onmousemove=»i18n(this)»>Примеры правильного кода для параметра < «args»: «none» >:

ignoreRestSiblings

ignoreRestSiblings option is a boolean (default: false ). Using a Rest Property it is possible to “omit” properties from an object, but by default the sibling properties are marked as “unused”. With this option enabled the rest property’s siblings are ignored.’ onmousemove=»i18n(this)»>Параметр ignoreRestSiblings является логическим (по умолчанию: false ). Используя Rest Property , можно «опустить» свойства объекта, но по умолчанию родственные свойства помечаются как «неиспользуемые». Если эта опция включена, соседние элементы остальных свойств игнорируются.

< «ignoreRestSiblings»: true >option:’ onmousemove=»i18n(this)»>Примеры правильного кода для параметра < «ignoreRestSiblings»: true >:

argsIgnorePattern

argsIgnorePattern option specifies exceptions not to check for usage: arguments whose names match a regexp pattern. For example, variables whose names begin with an underscore.» onmousemove=»i18n(this)»>Параметр argsIgnorePattern указывает исключения, которые не следует проверять на использование: аргументы, имена которых соответствуют шаблону регулярного выражения. Например, переменные, имена которых начинаются с подчеркивания.

< «argsIgnorePattern»: «^_» >option:’ onmousemove=»i18n(this)»>Примеры правильного кода для параметра < «argsIgnorePattern»: «^_» >:

destructuredArrayIgnorePattern

destructuredArrayIgnorePattern option specifies exceptions not to check for usage: elements of array destructuring patterns whose names match a regexp pattern. For example, variables whose names begin with an underscore.» onmousemove=»i18n(this)»>Параметр destructuredArrayIgnorePattern указывает исключения, использование которых не проверяется: элементы шаблонов деструктурирования массива, имена которых соответствуют шаблону регулярного выражения. Например, переменные, имена которых начинаются с подчеркивания.

caughtErrors

caughtErrors option is used for catch block arguments validation.» onmousemove=»i18n(this)»>Параметр caughtErrors используется для проверки аргументов блока catch .

У него две настройки:

  • none — do not check error objects. This is the default setting.» onmousemove=»i18n(this)»> none — не проверять ошибочные объекты. Это значение по умолчанию.
  • all — all named arguments must be used.» onmousemove=»i18n(this)»> all — должны использоваться все именованные аргументы.

caughtErrors: none

none .» onmousemove=»i18n(this)»>Отсутствие указания этого правила равносильно его none .

< «caughtErrors»: «none» >option:’ onmousemove=»i18n(this)»>Примеры правильного кода для параметра < «caughtErrors»: «none» >:

caughtErrors: all

< «caughtErrors»: «all» >option:’ onmousemove=»i18n(this)»>Примеры некорректного кода для параметра < «caughtErrors»: «all» >:

caughtErrorsIgnorePattern

caughtErrorsIgnorePattern option specifies exceptions not to check for usage: catch arguments whose names match a regexp pattern. For example, variables whose names begin with a string ‘ignore’.» onmousemove=»i18n(this)»>Параметр caughtErrorsIgnorePattern указывает исключения, использование которых не проверяется: перехватывайте аргументы, имена которых соответствуют шаблону регулярного выражения. Например, переменные, имена которых начинаются со строки «игнорировать».

Когда не использовать его

Если вы не хотите получать уведомления о неиспользуемых переменных или аргументах функций,вы можете смело отключить это правило.

Источник

Понравилась статья? Поделить с друзьями:
  • Use the pc health check app to check compatibility как исправить
  • Use sql syntax error
  • Use of important ошибка
  • Use error boundary
  • Use config tab is locked cisco как исправить