Поделиться через


Настройка проекта C++ для IntelliSense

В некоторых случаях может потребоваться вручную настроить проект C++ для правильной работы IntelliSense. For MSBuild projects (based on .vcxproj files), you can adjust settings in project properties. For non-MSBuild projects, you adjust settings in the CppProperties.json file in the root directory of the project. In some cases, you might need to create a hint file to help IntelliSense understand macro definitions. Интегрированная среда разработки Visual Studio помогает выявлять и устранять проблемы IntelliSense.

Single-file IntelliSense

When you open a file that isn't included in a project, Visual Studio provides some IntelliSense support, but by default no error squiggles are shown. If the Navigation Bar says Miscellaneous Files, then that probably explains why you don't see error squiggles under incorrect code, or why a preprocessor macro isn't defined.

Проверка списка ошибок

If a file isn't open in single-file mode, and IntelliSense isn't working correctly, the first place to check is the Error List window. Чтобы просмотреть все ошибки IntelliSense для текущего исходного файла вместе со всеми включенными файлами заголовков, выберите Build + IntelliSense в раскрывающемся списке:

Screenshot of the Error List window. Build + IntelliSense is selected in the filter dropdown.

IntelliSense produces a maximum of 1,000 errors. If there are more than 1,000 errors in the header files included by a source file, then the source file shows only a single error squiggle at the very start of the source file.

Убедитесь, что пути #include верны

Проекты MSBuild

If you run your builds outside of the Visual Studio IDE, and your builds are succeeding but IntelliSense is incorrect, it's possible that your command line is out of sync with the project settings for one or more configurations. Right-click on the project node in Solution Explorer and make sure that all #include paths are correct for the current configuration and platform. Если пути идентичны во всех конфигурациях и платформах, можно выбрать Все конфигурации и все платформы, а затем проверить правильность путей.

Screenshot that shows the Include Directories setting in the Configuration Properties section.

To see the current values for build macros such as VC_IncludePath, select the Include Directories dropdown. Then choose <Edit> and select the Macros button.

Проекты Makefile

For Makefile projects that are based on the NMake project template, choose NMake under Configuration Properties, and then choose Include search path in the IntelliSense category:

Screenshot that shows the Configuration Properties > N Make > Include Search Path setting.

CMake projects

For CMake projects, make sure that #include paths are specified correctly for all configurations in CMakeLists.txt. Other project types might require a CppProperties.json file. For more information, see Configure code navigation with CppProperties.json. Убедитесь, что пути верны для каждой конфигурации, определенной в файле.

If there's a syntax error in the CppProperties.json file, IntelliSense in the affected files is incorrect. Visual Studio displays the error in the Output Window.

Проблемы синтаксического анализа тегов

The tag parser is a fuzzy C++ parser that's used for browsing and navigation. It's fast but doesn't attempt to completely comprehend every code construct.

For example, it doesn't evaluate preprocessor macros, and therefore it might incorrectly parse code that makes heavy use of them. When the Tag Parser encounters an unfamiliar code construct, it might skip that entire region of code.

Существует два распространенных способа, которыми эта проблема проявляется в Visual Studio.

  1. The IDE offers to create a function definition for a function that is already defined.

  2. If the navigation bar shows an innermost macro, then the current function definition was skipped:

    Screenshot that shows the tag parser skipping the function definition.

    The code snippet shows a macro definition for do_if that is used inside of the function main. The tag parser doesn't understand the macro, so instead of the navigation dropdown showing that the name of the current function is main, it shows the name of the macro: do_if.

To fix these kinds of problems, add a file named cpp.hint to the root of your solution directory. For more information, see Hint Files.

Ошибки парсера тегов отображаются в окне списка ошибок .

Проверка параметров проекта с помощью журнала диагностики

To check whether the IntelliSense compiler is using correct compiler options, including Include Paths and Preprocessor macros, turn on Diagnostic Logging of IntelliSense command lines in Tools > Options > Text Editor > C/C++ > Advanced > Diagnostic Logging. Set Enable Logging to True, Logging Level to 5 (most verbose), and Logging Filter to 8 (IntelliSense logging).

The Output Window now shows the command lines that are passed to the IntelliSense compiler. Ниже приведен пример выходных данных:

[IntelliSense] Configuration Name: Debug|Win32
[IntelliSense] Toolset IntelliSense Identifier:
[IntelliSense] command line options:
/c
/I.
/IC:\Repo\Includes
/DWIN32
/DDEBUG
/D_DEBUG
/Zc:wchar_t-
/Zc:forScope
/Yustdafx.h

This information might help you understand why IntelliSense is providing inaccurate information. For example, if your project's Include directory contains $(MyVariable)\Include, and the diagnostic log shows /I\Include as an Include path, it means that $(MyVariable) wasn't evaluated, and was removed from the final include path.

About the IntelliSense build

Visual Studio использует выделенный компилятор C++ для создания и поддержания базы данных, которая управляет всеми функциями IntelliSense. Чтобы обеспечить синхронизацию базы данных IntelliSense с кодом, Visual Studio автоматически запускает сборки только IntelliSense в качестве фоновых задач в ответ на определенные изменения, внесенные в параметры проекта или исходные файлы.

Однако в некоторых случаях Visual Studio не может своевременно обновлять базу данных IntelliSense. For example, when you run a git pull or git checkout command, Visual Studio might take up to an hour to detect changes in the files. Вы можете принудительно выполнить повторное сканирование всех файлов в решении, щелкнув правой кнопкой мыши на узле проекта в 'Обозреватель решений' и выбрав 'Повторное сканирование решения'.

Troubleshoot IntelliSense build failures

An IntelliSense build doesn't produce binaries, but it can still fail. One possible cause for failure is custom .props or .targets files. In Visual Studio 2017 version 15.6 and later, IntelliSense-only build errors are logged to the Output window. To see them, set Show output from to Solution:

Screenshot that shows the Output window. The Show output from dropdown is set to Solution.

The error message might instruct you to enable design-time tracing:

error: Designtime build failed for project 'E:\src\MyProject\MyProject.vcxproj',
configuration 'Debug|x64'. IntelliSense might be unavailable.
Set environment variable TRACEDESIGNTIME=true and restart
Visual Studio to investigate.

If you set the environment variable TRACEDESIGNTIME to true and restart Visual Studio, you see a log file in the %TEMP% directory, which might help diagnose the build failure.

To learn more about TRACEDESIGNTIME environment variable, see Roslyn and Design-time builds. Информация в этих статьях относится к проектам C++.