Customizing default settings
You can override the default values for properties set in c_cpp_properties.json
.
The following C_Cpp.default.*
settings map to each of the properties in a configuration block of c_cpp_properties.json
. Namely:
C_Cpp.default.includePath : string[]
C_Cpp.default.defines : string[]
C_Cpp.default.compileCommands : string
C_Cpp.default.macFrameworkPath : string[]
C_Cpp.default.forcedInclude : string[]
C_Cpp.default.intelliSenseMode : string
C_Cpp.default.compilerPath : string
C_Cpp.default.cStandard : c89 | c99 | c11 | c17
C_Cpp.default.cppStandard : c++98 | c++03 | c++11 | c++14 | c++17 | c++20
C_Cpp.default.browse.path : string[]
C_Cpp.default.browse.databaseFilename : string
C_Cpp.default.browse.limitSymbolsToIncludedHeaders : boolean
These settings have all of the benefits of VS Code settings, meaning that they can have default, «User», «Workspace», and «Folder» values. So you can set a global value for C_Cpp.default.cppStandard
in your «User» settings and have it apply to all of the folders you open. If any one folder needs a different value, you can override the value by adding a «Folder» or «Workspace» value.
This property of VS Code settings allows you to configure each of your workspaces independently — making the c_cpp_properties.json
file optional.
Updated c_cpp_properties.json
syntax
A special variable has been added to the accepted syntax of c_cpp_properties.json
that will instruct the extension to insert the value from the VS Code settings mentioned above. If you set the value of any setting in c_cpp_properties.json
to «${default}» it will instruct the extension to read the VS Code default setting for that property and insert it. For example:
"configurations": [
{
"name": "Win32",
"includePath": [
"additional/paths",
"${default}"
],
"defines": [
"${default}"
],
"macFrameworkPath": [
"${default}",
"additional/paths"
],
"forcedInclude": [
"${default}",
"additional/paths"
],
"compileCommands": "${default}",
"browse": {
"limitSymbolsToIncludedHeaders": true,
"databaseFilename": "${default}",
"path": [
"${default}",
"additional/paths"
]
},
"intelliSenseMode": "${default}",
"cStandard": "${default}",
"cppStandard": "${default}",
"compilerPath": "${default}"
}
],
Note that for the properties that accept string[], the syntax proposed above allows you to augment the VS Code setting with additional values, thus allowing you to have common paths listed in the VS Code settings and configuration-specific settings in c_cpp_properties.json
.
If a property is missing from c_cpp_properties.json
, the extension will use the value in the VS Code setting. If a developer assigns values to all of the settings that apply for a given folder, then c_cpp_properties.json
could be removed from the .vscode folder as it will no longer be needed.
For in-depth information about the c_cpp_properties.json settings file, See c_cpp_properties.json reference.
System includes
A new setting will be added that allows you specify the system include path separate from the folder’s include path. If this setting has a value, then the system include path the extension gets from the compiler specified in the compilerPath
setting will not be added to the path array that the extension uses for IntelliSense. We may want to provide a VS Code command to populate this value from the compiler’s default for users who are interested in using it in case they want to make some modifications to the defaults.
C_Cpp.default.systemIncludePath : string[]
System include path/defines resolution strategies
The extension determines the system includePath and defines to send to the IntelliSense engine in the following manner:
-
If
compileCommands
has a valid value and the file open in the editor is in the database, use the compile command in the database entry to determine the include path and defines.- The system include path and defines are determined using the following logic (in order):
- If
systemIncludePath
has a value, use it (continue to the next step to search for system defines). - If
compilerPath
is valid, query it. - Interpret the first argument in the command as the compiler and attempt to query it.
- If
compilerPath
is «», use an empty array for system include path and defines. - If
compilerPath
is undefined, look for a compiler on the system and query it.
- If
- The system include path and defines are determined using the following logic (in order):
-
If
compileCommands
is invalid or the current file is not listed in the database, use theincludePath
anddefines
properties in the configuration for IntelliSense.- The system include path and defines are determined using the following logic (in order):
- If
systemIncludePath
has a value, use it (continue to the next step to search for system defines). - If
compilerPath
is valid, query it. - If
compilerPath
is «», use an empty array for system include path and defines (they are assumed to be in theincludePath
anddefines
for the current config already). - If
compilerPath
is undefined, look for a compiler on the system and query it.
- If
- The system include path and defines are determined using the following logic (in order):
System includes should not be added to the includePath
or browse.path
variables. If the extension detects any system include paths in the includePath
property it will silently remove them so that it can ensure system include paths are added last and in the correct order (this is especially important for GCC/Clang).
Enhanced semantic colorization
When IntelliSense is enabled, the Visual Studio Code C/C++ extension supports semantic colorization. See Enhanced colorization for more details about setting colors for classes, functions, variables and so on.
Extension logging
If you are experiencing a problem with the extension that we can’t diagnose based on information in your issue report, we might ask you to enable logging and send us your logs. See C/C++ extension logging for information about how to collect logs.
5/21/2020
From the official documentation of the C/C++ extension:
Configuring includePath for better IntelliSense results
If you’re seeing the following message when opening a folder in Visual Studio Code, it means the C++ IntelliSense engine needs additional information about the paths in which your include files are located.
Where are the include paths defined?
The include paths are defined in the "includePath"
setting in a file called c_cpp_properties.json located in the .vscode directory in the opened folder.
You can create or open this file by either using the "C/Cpp: Edit Configurations"
command in the command palette or by selecting "Edit "includePath" setting"
in the light bulb menu (see the screenshot below). The quickest way to locate a light bulb is to scroll to the top of the source file and click on any green squiggle that shows up under a #include statement.
When a folder is opened, the extension attempts to locate your system headers based on your operating system, but it does not know about any other libraries that your project depends on. You can hover over the green squiggles or open the Problems window to understand which headers the IntelliSense engine is unable to open — sometimes it’s the dependent headers that can’t be located.
How can I specify the include paths?
You can specify the remaining paths using one of the techniques described below.
-
Use compile_commands.json file to supply includePaths and defines information
The extension can get the information for
"includePath"
and"defines"
from a compile_commands.json file, which can be auto-generated by many build systems such as CMake and Ninja. Look for the section where your current configuration is defined (by default there’s one configuration per operating system, such as «Win32 or «Mac»), and set the"compileCommands"
property in c_cpp_properties.json to the full path to your compile_commands.json file and the extension will use that instead of the"includes"
and"defines"
properties for IntelliSense. -
Use the light bulb suggestions to auto-resolve includePath
The first thing to try is to leverage the light bulb path suggestions to auto-resolve the include paths. When you open a folder, the extension will recursively search for potential include paths that match the header files your code is using based on the paths set by the
"browse.path"
setting in c_cpp_properties.json. Click on the green squiggles under #include statements and you’ll see a light bulb offering suggestions of paths that will allow IntelliSense to resolve the included file.If you don’t see path suggestions in the light bulb, try adding the root folder where the headers are likely located in to the
"browse.path"
setting in c_cpp_properties.json. This allows the extension to recursively search in these folders and offer more suggestions in the light bulb as the search process goes on. -
Manually add include paths
If none of the above fully resolves the paths, you could manually specify the paths to the headers that your project depends on in the c_cpp_properties.json file. Look for the section where your current configuration is defined (by default there’s one configuration per OS, such as «Win32 or «Mac»), and add your paths in the
"includePath"
setting and defines in the"defines"
setting. For example, the following screenshot shows a snippet of the file specifying path for the Mac configuration.Also, for MinGW, as the documentation of the extension explains you may ask gcc/g++ to list its own include files:
gcc -v -E -x c++ nul
Verify the include paths are correctly resolved
There are two ways to verify that the include paths are correctly resolved:
- The green squiggles in the source file are no longer showing
- Error messages are cleared in the Problems window
This indicates that the IntelliSense engine has got the include paths resolved so you can start enjoying the full IntelliSense for your C or C++ code for the current translation unit. Note that you may still see errors on other files if they belong to a different translation unit that requires additional include paths to be configured.
If this didn’t resolve your issue then, check out the configuration for MinGW below and try setting the appropriate location for your Cygwin installation for the respective/similar header files & folders.
Configuring MinGW
c_cpp_properties.json reference guide
Order | Area | TOCTitle | ContentId | PageTitle | DateApproved | MetaDescription |
---|---|---|---|---|---|---|
12 |
cpp |
Settings |
4E34F6AF-BFC6-4BBB-8464-2E50C85AE826 |
Customize default settings in Visual Studio Code C++ projects |
5/21/2020 |
How to customize semantic colorization of C++ code in Visual Studio Code. |
Customizing default settings
You can override the default values for properties set in c_cpp_properties.json
.
Visual Studio Code settings
The following C_Cpp.default.*
settings map to each of the properties in a configuration block of c_cpp_properties.json
. Namely:
C_Cpp.default.includePath : string[] C_Cpp.default.defines : string[] C_Cpp.default.compileCommands : string C_Cpp.default.macFrameworkPath : string[] C_Cpp.default.forcedInclude : string[] C_Cpp.default.intelliSenseMode : string C_Cpp.default.compilerPath : string C_Cpp.default.cStandard : c89 | c99 | c11 | c17 C_Cpp.default.cppStandard : c++98 | c++03 | c++11 | c++14 | c++17 | c++20 C_Cpp.default.browse.path : string[] C_Cpp.default.browse.databaseFilename : string C_Cpp.default.browse.limitSymbolsToIncludedHeaders : boolean
These settings have all of the benefits of VS Code settings, meaning that they can have default, «User», «Workspace», and «Folder» values. So you can set a global value for C_Cpp.default.cppStandard
in your «User» settings and have it apply to all of the folders you open. If any one folder needs a different value, you can override the value by adding a «Folder» or «Workspace» value.
This property of VS Code settings allows you to configure each of your workspaces independently — making the c_cpp_properties.json
file optional.
Updated c_cpp_properties.json
syntax
A special variable has been added to the accepted syntax of c_cpp_properties.json
that will instruct the extension to insert the value from the VS Code settings mentioned above. If you set the value of any setting in c_cpp_properties.json
to «${default}» it will instruct the extension to read the VS Code default setting for that property and insert it. For example:
"configurations": [ { "name": "Win32", "includePath": [ "additional/paths", "${default}" ], "defines": [ "${default}" ], "macFrameworkPath": [ "${default}", "additional/paths" ], "forcedInclude": [ "${default}", "additional/paths" ], "compileCommands": "${default}", "browse": { "limitSymbolsToIncludedHeaders": true, "databaseFilename": "${default}", "path": [ "${default}", "additional/paths" ] }, "intelliSenseMode": "${default}", "cStandard": "${default}", "cppStandard": "${default}", "compilerPath": "${default}" } ],
Note that for the properties that accept string[], the syntax proposed above allows you to augment the VS Code setting with additional values, thus allowing you to have common paths listed in the VS Code settings and configuration-specific settings in c_cpp_properties.json
.
If a property is missing from c_cpp_properties.json
, the extension will use the value in the VS Code setting. If a developer assigns values to all of the settings that apply for a given folder, then c_cpp_properties.json
could be removed from the .vscode folder as it will no longer be needed.
For in-depth information about the c_cpp_properties.json settings file, See c_cpp_properties.json reference.
System includes
A new setting will be added that allows you specify the system include path separate from the folder’s include path. If this setting has a value, then the system include path the extension gets from the compiler specified in the compilerPath
setting will not be added to the path array that the extension uses for IntelliSense. We may want to provide a VS Code command to populate this value from the compiler’s default for users who are interested in using it in case they want to make some modifications to the defaults.
C_Cpp.default.systemIncludePath : string[]
System include path/defines resolution strategies
The extension determines the system includePath and defines to send to the IntelliSense engine in the following manner:
-
If
compileCommands
has a valid value and the file open in the editor is in the database, use the compile command in the database entry to determine the include path and defines.- The system include path and defines are determined using the following logic (in order):
- If
systemIncludePath
has a value, use it (continue to the next step to search for system defines). - If
compilerPath
is valid, query it. - Interpret the first argument in the command as the compiler and attempt to query it.
- If
compilerPath
is «», use an empty array for system include path and defines. - If
compilerPath
is undefined, look for a compiler on the system and query it.
- If
- The system include path and defines are determined using the following logic (in order):
-
If
compileCommands
is invalid or the current file is not listed in the database, use theincludePath
anddefines
properties in the configuration for IntelliSense.- The system include path and defines are determined using the following logic (in order):
- If
systemIncludePath
has a value, use it (continue to the next step to search for system defines). - If
compilerPath
is valid, query it. - If
compilerPath
is «», use an empty array for system include path and defines (they are assumed to be in theincludePath
anddefines
for the current config already). - If
compilerPath
is undefined, look for a compiler on the system and query it.
- If
- The system include path and defines are determined using the following logic (in order):
System includes should not be added to the includePath
or browse.path
variables. If the extension detects any system include paths in the includePath
property it will silently remove them so that it can ensure system include paths are added last and in the correct order (this is especially important for GCC/Clang).
Enhanced semantic colorization
When IntelliSense is enabled, the Visual Studio Code C/C++ extension supports semantic colorization. See Enhanced colorization for more details about setting colors for classes, functions, variables and so on.
Extension logging
If you are experiencing a problem with the extension that we can’t diagnose based on information in your issue report, we might ask you to enable logging and send us your logs. See C/C++ extension logging for information about how to collect logs.
This article will show how to use Visual Studio Code’s Include Paths for C/C++ to assist ARM programming. While writing code, Visual Studio Code with the C/C++ plugin has a number of handy features:
- Highlighting of syntax
- We check for errors as we type, and
- Automatic code completion, in which it makes educated predictions as we type.
This can help us write more quickly and with fewer errors. These capabilities, however, will not work well or at all if the plugin is not properly configured.
Visual Studio Code and the C/C++ language plugin need to be able to locate all of the header files referenced in our programme in order to understand it.
The lightbulb to the left of the error will be seen if the pointer is on it. Then update the “includePath” setting by clicking that. In our project, VSCode will generate and open a file called “c cpp properties.json” in the “.vscode” folder. This will have setups for Mac, Linux, and Win32 by default. These include default includePaths that are appropriate for desktop programmes but unsuitable for ARM.
There are two paths in this area. The first, “includePath,” tells VSCode where to look for headers so it can examine our code. This is not recursive, unlike GCC; we must explicitly identify each folder containing headers that are referenced, either directly or indirectly.
The second section with just “path” is used by IntelliSense to suggest things for us.
This is the initial c_cpp_properties.json file:
{ "configurations": [ { "name": "WIN32", "includePath": [ "${workspaceFolder}/**", "E:\ti\TivaWare_C_Series-2.2.0.295" ], "defines": [ "_DEBUG", "PART_TM4C123GH6PM" ], "compilerPath": "C:\ProgramData\chocolatey\bin\arm-none-eabi-gcc", "cStandard": "c99", "cppStandard": "gnu++17", "intelliSenseMode": "gcc-arm", "configurationProvider": "ms-vscode.cmake-tools" }, { "name": "LINUX", "includePath": [ "${workspaceFolder}/**", "/home/jshankar/ti/TivaWare_C_Series-2.2.0.295" ], "defines": [ "_DEBUG", "PART_TM4C123GH6PM" ], "compilerPath": "/opt/toolchains/gcc-arm-none-eabi-10.3-2021.10/bin/arm-none-eabi-gcc", "cStandard": "c99", "cppStandard": "gnu++17", "intelliSenseMode": "gcc-arm", "configurationProvider": "ms-vscode.cmake-tools" } ], "version": 4 }
- name: arbitrary name for the configuration
- includePath: list here all locations where IntelliSense shall search for header files. It automatically will use the ones located in the toolchain (compiler) installation. The ‘**’ notation means it will search recursively that folder
- defines: list all the extra defines which shall be considered.
- forcedInclude: if using the -include compiler option, make sure you list that file here
- compilerPath: path to the compiler executable.
- cStandard and cppStandard: the C and C++ standard to be used
- intelliSenseMode: mode to be used. ‘gcc-arm’ is considered legacy, but not sure what to use otherwise for ARM?
P1XELCORE 0 / 0 / 0 Регистрация: 11.04.2013 Сообщений: 78 |
||||||||||||
1 |
||||||||||||
10.08.2020, 16:18. Показов 78174. Ответов 26 Метки нет (Все метки)
Всем привет, хотел начать писать на плюсах в vs code, установил, всё гуд, mingw поставил, настроил всё, когда начинаю компилировать прогу выдает ошибки «Обнаружены ошибки #include. Измените includePath», что он хочет от меня?? (os win10) Это файл c_cpp_properties.json
launch.json
tasks.json
__________________
0 |
Programming Эксперт 94731 / 64177 / 26122 Регистрация: 12.04.2006 Сообщений: 116,782 |
10.08.2020, 16:18 |
26 |
406 / 290 / 119 Регистрация: 18.07.2017 Сообщений: 1,346 |
|
11.08.2020, 13:06 |
2 |
Обнаружены ошибки #include. Измените includePath», что он хочет от меня? Тебя на шелле, чтоли читать учили, раз ты не видишь то, что после хеш-тега?
«includePath»: [ Проверь наличие таких директорий, либо поправь пути если они в другом месте.
0 |
0 / 0 / 0 Регистрация: 11.04.2013 Сообщений: 78 |
|
11.08.2020, 13:15 [ТС] |
3 |
Проверь наличие таких директорий, либо поправь пути если они в другом месте. я сам прописал этот путь, было бы странно если бы там не было этих директорий)
0 |
фрилансер 4479 / 3989 / 870 Регистрация: 11.10.2019 Сообщений: 10,507 |
|
11.08.2020, 13:50 |
4 |
P1XELCORE, ${workspaceFolder}/** звёзды вроде не к месту ? редактируй эти настройки через визард, тогда будет меньше ошибок
0 |
0 / 0 / 0 Регистрация: 11.04.2013 Сообщений: 78 |
|
11.08.2020, 14:12 [ТС] |
5 |
звёзды вроде не к месту ? Они по дефолту стояли в этом файле. Как я понял не просто так, т.к. про них написано в справочнике «Если путь заканчивается на /**, подсистема IntelliSense будет выполнять рекурсивный поиск файлов заголовков, начиная с этого каталога.»
редактируй эти настройки через визард, тогда будет меньше ошибок не совсем понимаю что значит редактировать через визард)
0 |
фрилансер 4479 / 3989 / 870 Регистрация: 11.10.2019 Сообщений: 10,507 |
|
11.08.2020, 14:19 |
6 |
через визард то есть, напрямую файл править не надо, надо открывать свойства проекта — зависимости, пути и т.д. Там же можно посмотреть, во что раскрываются макросы вида ${…} Добавлено через 1 минуту
«Обнаружены ошибки #include. Измените includePath», а покажи скрин, кстати
1 |
0 / 0 / 0 Регистрация: 11.04.2013 Сообщений: 78 |
|
11.08.2020, 14:58 [ТС] |
7 |
а покажи скрин, кстати
0 |
фрилансер 4479 / 3989 / 870 Регистрация: 11.10.2019 Сообщений: 10,507 |
|
11.08.2020, 15:07 |
8 |
P1XELCORE, iostream и настройки тут ни при чём
1 |
0 / 0 / 0 Регистрация: 11.04.2013 Сообщений: 78 |
|
11.08.2020, 15:08 [ТС] |
9 |
в самом коде подчеркивает проблему именно подключение библиотеки, если выбрать «Изменить параметр includePath», то кидает на вкладку изменения конфигурации IntelliSense, там по логике прописываются пути для компилятора и библиотек
0 |
0 / 0 / 0 Регистрация: 11.04.2013 Сообщений: 78 |
|
11.08.2020, 15:09 [ТС] |
10 |
P1XELCORE, iostream действительно, спасибо огромное) запустилось! только теперь ругается консоль отладки, но всё же спасибо)
0 |
фрилансер 4479 / 3989 / 870 Регистрация: 11.10.2019 Сообщений: 10,507 |
|
11.08.2020, 19:31 |
11 |
теперь ругается консоль отладки как ругается ?
0 |
0 / 0 / 0 Регистрация: 11.04.2013 Сообщений: 78 |
|
12.08.2020, 08:46 [ТС] |
12 |
как ругается ?
вот эти строки о том что какие-то символы загружены, они так и должны быть? мне кажется в окно вывода должно просто хеллоу ворд выходить)
0 |
фрилансер 4479 / 3989 / 870 Регистрация: 11.10.2019 Сообщений: 10,507 |
|
12.08.2020, 09:05 |
13 |
P1XELCORE, так и смотри в окне вывода. У тебя всё там не на английском, но предполагаю, это вкладка «выходные данные» а может и «терминал». Или вообще окно в настройках не включено Добавлено через 3 минуты
0 |
406 / 290 / 119 Регистрация: 18.07.2017 Сообщений: 1,346 |
|
12.08.2020, 09:41 |
14 |
какие-то символы загружены Судя по всему это загрузка метаданных для дебаггера из модулей, которые будут использоваться твоей программой.
мне кажется в окно вывода должно просто хеллоу ворд выходить А мне кажеся, что дебаггеру плевать на ввод-вывод, если не поставлена точка останова. Если у этой консоли та же логика что и в gdb, то туда нужно вводить название переменных либо выражения. И дебаггер покажет значение переменной, либо рассчитает выражение.
программу где нужно вводить входные данные, то она отладку не проходит вовсе Всмысле не проходит? Зависает? Ну так может нужно данные вводить не в консоль отладки, а в окно самой программы? У тебя там консолька не всплывает случаем на фоне?
0 |
0 / 0 / 0 Регистрация: 11.04.2013 Сообщений: 78 |
|
12.08.2020, 10:21 [ТС] |
15 |
но предполагаю, это вкладка «выходные данные» Во вкладке «выходные данные» пусто всегда, а в терминале вот такое выходит когда без проблем компилируется Миниатюры
0 |
0 / 0 / 0 Регистрация: 11.04.2013 Сообщений: 78 |
|
12.08.2020, 10:25 [ТС] |
16 |
Всмысле не проходит? Зависает? Ну так может нужно данные вводить не в консоль отладки, а в окно самой программы? У тебя там консолька не всплывает случаем на фоне? Консолька не всплывает для ввода данных, просто опять что-то пишет в консоль отладки и в терминал Миниатюры
0 |
Алексей1153 фрилансер 4479 / 3989 / 870 Регистрация: 11.10.2019 Сообщений: 10,507 |
||||
12.08.2020, 10:46 |
17 |
|||
P1XELCORE, кстати, да, у тебя приложение то консольное? Тогда консоль должна быть на экране. А в окно отладки, которое снизу, вывод в студии производится через TRACE/TRACE0/OutputDebugString (понадобится заголовок <Windows.h> ) Добавлено через 2 минуты
0 |
406 / 290 / 119 Регистрация: 18.07.2017 Сообщений: 1,346 |
|
12.08.2020, 10:53 |
18 |
просто опять что-то пишет в консоль отладки и в терминал Ну ок, а почему точку останова до сих пор не поставил? Как у тебя дебаггер будет стопать программу?
0 |
0 / 0 / 0 Регистрация: 11.04.2013 Сообщений: 78 |
|
12.08.2020, 11:06 [ТС] |
19 |
Ну ок, а почему точку останова до сих пор не поставил? Как у тебя дебаггер будет стопать программу? Поставил) всё так же) Миниатюры
0 |
0 / 0 / 0 Регистрация: 11.04.2013 Сообщений: 78 |
|
12.08.2020, 11:09 [ТС] |
20 |
кстати, да, у тебя приложение то консольное? ну, если консолька не выходит при запуске программы, значит не консольное?)
0 |
Я новичок в использовании кода Visual Studio, и я понятия не имею, что я делаю.
Я искал (возможно, не достаточно), но я не могу найти просто простое объяснение для кого-то, как я, о том, как настроить c_cpp_properties.json
файл, к которому меня перенаправляют всякий раз, когда я нажимаю на желтую лампочку рядом с линией, которая подчеркнута зеленым загогулином.
Пример лампочки
c_cpp_properties.json
Я просто хочу знать, что положить в .json
заставить IntelliSense работать правильно
7
Решение
От:
https://code.visualstudio.com/docs/languages/cpp
Ниже вы можете видеть, что путь включения MinGW C ++ был добавлен в browse.path для Windows:
{
"name": "Win32",
"includePath": [
"${workspaceRoot}"],
"defines": [
"_DEBUG",
"UNICODE"],
"intelliSenseMode": "msvc-x64",
"browse": {
"path": [
"${workspaceRoot}",
"C:\MinGW\lib\gcc\mingw32\6.3.0\include\c++"],
"limitSymbolsToIncludedHeaders": true,
"databaseFilename": ""}
}
Надеюсь, это поможет! 🙂
1
Другие решения
Из официальной документации расширения C / C ++:
Если при открытии папки в VS Code вы видите следующее сообщение, это означает, что движку C ++ IntelliSense требуется дополнительная информация о путях, в которых находятся ваши включаемые файлы.
Где определены пути включения?
Пути включения определены в "includePath"
установка в файле с именем c_cpp_properties.json находится в каталоге .vscode в открытой папке.
Вы можете создать или открыть этот файл, используя "C/Cpp: Edit Configurations"
Команда в палитре команд или выбрав "Edit "includePath" setting"
в меню лампочки (см. скриншот ниже). Самый быстрый способ найти лампочку — это прокрутить верхнюю часть исходного файла и щелкнуть на любой зеленой загадке, которая появляется под оператором #include.
Когда папка открыта, расширение пытается найти системные заголовки на основе вашей операционной системы, но не знает ни о каких других библиотеках, от которых зависит ваш проект. Вы можете навести курсор на зеленые загогулины или открыть окно «Проблемы», чтобы понять, какие заголовки механизм IntelliSense не может открыть — иногда это не могут быть найдены зависимые заголовки.
Как указать пути включения?
Вы можете указать оставшиеся пути, используя один из методов, описанных ниже.
1. Используйте файл compile_commands.json для предоставления includePaths и определения информации
Расширение может получить информацию для "includePath"
а также "defines"
из файла compile_commands.json, который может автоматически генерироваться многими системами сборки, такими как CMake и Ninja. Найдите раздел, в котором определена текущая конфигурация (по умолчанию для каждой ОС существует одна конфигурация, например, «Win32 или« Mac »), и установите "compileCommands"
недвижимость в c_cpp_properties.json полный путь к файлу compile_commands.json, и расширение будет использовать его вместо "includes"
а также "defines"
свойства для IntelliSense.
2. Используйте предложения лампочки для автоматического разрешения includePath
Первое, что нужно попробовать, — это использовать подсказки пути лампочки для автоматического разрешения включаемых путей. Когда вы открываете папку, расширение будет рекурсивно поиск возможных путей включения, соответствующих заголовочным файлам, которые использует ваш код, на основе путей, заданных "browse.path"
установка в c_cpp_properties.json. Нажмите на зеленые загогулины под заявлениями #include, и вы увидите лампочку, предлагающую пути, которые позволят IntelliSense разрешить включенный файл.
Если вы не видите подсказки пути в лампочке, попробуйте добавить корневую папку, в которой заголовки, вероятно, расположены в "browse.path"
установка в c_cpp_properties.json. Это позволяет расширению рекурсивно искать в этих папках и предлагать больше предложений в лампочке в процессе поиска.
3. Вручную добавить пути включения
Если ни один из приведенных выше способов полностью не разрешает пути, вы можете вручную указать пути к заголовкам, от которых зависит ваш проект, в c_cpp_properties.json файл. Найдите раздел, в котором определена ваша текущая конфигурация (по умолчанию для каждой ОС существует одна конфигурация, например, «Win32 или« Mac »), и добавьте ваши пути в "includePath"
установка и определяет в "defines"
установка. Например, на следующем снимке экрана показан фрагмент файла с указанием пути для конфигурации Mac.
Кроме того, для MinGW, как объясняет документация расширения ты можешь спросить GCC / G ++ перечислить свои собственные включаемые файлы:
gcc -v -E -x c++ nul
Убедитесь, что пути включения правильно разрешены
Есть два способа проверить правильность разрешения путей включения:
- Зеленые загогулины в исходном файле больше не отображаются
- Сообщения об ошибках очищаются в окне «Проблемы».
Это указывает на то, что в движке IntelliSense разрешены пути включения, поэтому вы можете начать пользоваться полным IntelliSense для своего кода C или C ++ для текущего модуля перевода. Обратите внимание, что вы все равно можете видеть ошибки в других файлах, если они принадлежат другому модулю перевода, для которого требуется настроить дополнительные пути включения.
Если это не решило вашу проблему, проверьте конфигурацию MinGW ниже и попробуйте установить подходящее место для вашей установки Cygwin для соответствующих / похожих заголовочных файлов. & папки.
Настройка MinGW
c_cpp_properties.json справочное руководство
-3
I’ve managed to get IntelliSense to work but important disclaimer, I barely have an understanding of how this works and mostly copied and pasted other people’s files. Still if it works, it works.
Essentially, you want to add your include paths to your c_cpp_properties.json found from the .vscode workspace folder. In case of a Multi-root Workspace, workspace settings are located inside the workspace configuration file. Not sure if it’s the same for other operating systems and other compilers but here’s how to configure C++ IntelliSense it with MinGW and windows:
-
You’ll be able to find this .json file by clicking on the yellow light bulb beside the error squiggles.
-
From there, find your operating system
-
Find «browse» then under «path», add the paths for the include.
-
Once you do that and refresh vs code, the squiggles will still appear, but now you have the option to add includePaths.
Take a look at my .json file. I changed intelliSenseMode to «clang-x64» then put some file paths in «browse»: { «path»[] }
"C:/MinGW/lib/gcc/mingw32/6.3.0/include",
"C:/MinGW/lib/gcc/mingw32/6.3.0/include-fixed",
"C:/MinGW/include/*"
Above are the include statements. Below is part of my c_cpp_properties.json.
"name": "Win32",
"intelliSenseMode": "clang-x64",
"includePath": [
"${workspaceRoot}",
"C:/MinGW/lib/gcc/mingw32/6.3.0/include/c++",
"C:/MinGW/lib/gcc/mingw32/6.3.0/include/c++/mingw32",
"C:/MinGW/lib/gcc/mingw32/6.3.0/include/c++/backward",
"C:/MinGW/lib/gcc/mingw32/6.3.0/include",
"C:/MinGW/include",
"C:/MinGW/lib/gcc/mingw32/6.3.0/include-fixed",
"C:/MinGW/lib/gcc/mingw32/6.3.0/include/objc/c++/tr1",
"C:/MinGW/lib/gcc/mingw32/6.3.0/include/objc/c++",
"C:/MinGW/lib/gcc/mingw32/6.3.0/include/objc/c++/mingw32"
],
"defines": [
"_DEBUG",
"UNICODE",
"__GNUC__=6",
"__cdecl=__attribute__((__cdecl__))"
],
"browse": {
"path": [
"C:/MinGW/lib/gcc/mingw32/6.3.0/include",
"C:/MinGW/lib/gcc/mingw32/6.3.0/include-fixed",
"C:/MinGW/include/*"
],
"limitSymbolsToIncludedHeaders": true,
"databaseFilename": ""
},
"cStandard": "c11",
"cppStandard": "c++17"