Измените include path visual studio code
This article explains the scheme for the c_cpp_properties.json settings file.
Example
Top-level properties
env An array of user-defined variables that will be available for substitution in the configurations via the standard environment variable syntax: $> or $> . Strings and arrays of strings are accepted.
configurations An array of configuration objects that provide the IntelliSense engine with information about your project and your preferences. By default, the extension creates a configuration for you based on your operating system. You may also add additional configurations.
version We recommend you don't edit this field. It tracks the current version of the c_cpp_properties.json file so that the extension knows what properties and settings should be present and how to upgrade this file to the latest version.
Configuration properties
name A friendly name that identifies a configuration. Linux , Mac , and Win32 are special identifiers for configurations that will be autoselected on those platforms. The status bar in VS Code will show you which configuration is active. You can also click on the label in the status bar to change the active configuration.
compilerPath (optional) The full path to the compiler you use to build your project, for example /usr/bin/gcc , to enable more accurate IntelliSense. The extension will query the compiler to determine the system include paths and default defines to use for IntelliSense.
Putting "compilerPath": "" (empty string) will skip querying a compiler. This is useful if a specified compiler doesn't support the arguments that are used for the query, as the extension will default back to any compiler it can find (like Visual C). Leaving out the compilerPath property does not skip the query.
compilerArgs (optional) Compiler arguments to modify the includes or defines used, for example -nostdinc++ , -m32 , etc.
intelliSenseMode The IntelliSense mode to use that maps to an architecture-specific variant of MSVC, gcc, or Clang. If not set or if set to $ , the extension will choose the default for that platform.
- Windows: msvc-x64
- Linux: gcc-x64
- macOS: clang-x64
defines A list of preprocessor definitions for the IntelliSense engine to use while parsing files. Optionally, use = to set a value, for example VERSION=1 .
cStandard The version of the C language standard to use for IntelliSense.
cppStandard The version of the C++ language standard to use for IntelliSense.
configurationProvider The ID of a VS Code extension that can provide IntelliSense configuration information for source files. For example, use the VS Code extension ID ms-vscode.cmake-tools to provide configuration information from the CMake Tools extension.
windowsSdkVersion The versions of the Windows SDK include path to use on Windows, for example 10.0.17134.0 .
macFrameworkPath A list of paths for the IntelliSense engine to use while searching for included headers from Mac frameworks. Only supported on configurations for macOS.
forcedInclude (optional) A list of files that should be included before any other characters in the source file are processed. Files are included in the order listed.
compileCommands (optional) The full path to the compile_commands.json file for the workspace. The include paths and defines discovered in this file will be used instead of the values set for includePath and defines settings. If the compile commands database does not contain an entry for the translation unit that corresponds to the file you opened in the editor, then a warning message will appear and the extension will use the includePath and defines settings instead.
For more information about the file format, see the Clang documentation. Some build systems, such as CMake, simplify generating this file.
Browse properties
path A list of paths for the Tag Parser to search for headers included by your source files. If omitted, includePath will be used as the path . Searching on these paths is recursive by default. Specify * to indicate non-recursive search. For example: $ will search through all subdirectories while $/* will not.
limitSymbolsToIncludedHeaders When true, the Tag Parser will only parse code files that have been directly or indirectly included by a source file in $ . When false, the Tag Parser will parse all code files found in the paths specified in the browse.path list.
databaseFilename The path to the generated symbol database. This property instructs the extension to save the Tag Parser's symbol database somewhere other than the workspace's default storage location. If a relative path is specified, it will be made relative to the workspace's default storage location, not the workspace folder itself. The $ variable can be used to specify a path relative to the workspace folder (for example $/.vscode/browse.vc.db )
Supported variables
You can allow tasks.json or launch.json to query the current active configuration from c_cpp_properties.json . To do this, use the variable $ as an argument in a tasks.json or launch.json script.
I'm trying to build C/C++ in Visual Studio Code. I installed C/C++ and all the relevant extensions.
How and where can I add include paths in the configurations below?
13 Answers 13
A more current take on the situation. During 2018, the C++ extension added another option to the configuration compilerPath of the c_cpp_properties.json file;
compilerPath (optional) The absolute path to the compiler you use to build your project. The extension will query the compiler to determine the system include paths and default defines to use for IntelliSense.
If used, the includePath would not be needed since the IntelliSense will use the compiler to figure out the system include paths.
How and where can I add include paths in the configurations below?
The list is a string array, hence adding an include path would look something like;
The linked source has a gif showing the format for the Win32 configuration, but the same applies to the others.
The above sample includes the SDK (OSX 10.11) path if Xcode is installed.
Note I find it can take a while to update once the include path has been changed.
The cpptools extension can be found here.
Further documentation (from Microsoft) on the C++ language support in VSCode can be found here.
For the sake of preservation (from the discussion), the following are basic snippets for the contents of the tasks.json file to compile and execute either a C++ file, or a C file. They allow for spaces in the file name (requires escaping the additional quotes in the json using \" ). The shell is used as the runner, thus allowing the compilation ( clang. ) and the execution ( && ./a.out ) of the program. It also assumes that the tasks.json "lives" in the local workspace (under the directory .vscode). Further task.json details, such as supported variables etc. can be found here.
Have in mind that you can use /** for a recursive include: "includePath":[ "C:/path/to/all/includes/**" ] .
In newer versions of the C/C++ extension, it is recommended to use the compilerPath property to set the system includes/defines instead of adding them to the includePath property.
For everybody that falls off google, in here, this is the fix for VSCode 1.40 (2019):
Open the global settings.json: File > Preferences > Settings
Then select the tab 'User', open the section 'Extensions', click on 'C/C++'. Then scroll the right panel till you find a 'Edit in settings.json' button.
Last, you add the "C_Cpp.default.includePath" section. The code provided there is from my own system (Windows 7). You can use it as a base for your own libraries paths. (Remember to change the YOUR USERNAME to your correct system (my case windows) username)
(edit info: There is a problem with the recursion of my approach. VSCode doesn't like multiple definitions for the same thing. I solved it with "C_Cpp.intelliSenseEngine": "Tag Parser" )
the code before line 7, on the settings.json has nothing to do with arduino or includePath. You may not copy that.
JSON section to add to settings.json:
Hi @Lorenz. Are you sure that the path to the header ( *.h ) file(s) are correct? Are you sure that it is on the "Program Files" folder and not on "Program Files (x86)" instead? Also, the slashes should be the / one, and not the backslash ``.
@Vitox: thank you. It's worth noting that I first added my include directories without adding that last line, "C_Cpp.intelliSenseEngine": "Tag Parser" , and it did not work. After adding it, it works great.
For Mac users who only have Command Line Tools instead of Xcode, check the /Library/Developer/CommandLineTools directory, for example::
You probably need to adjust the path if you have different version of Command Line Tools installed.
Note: You can also open/generate the c_cpp_properties.json file via the C/Cpp: Edit Configurations command from the Command Palette (⇧⌘P).
In the current c_cpp_properties.json file, it states at the top of the file: ". WARNING . ": "PLEASE DO NOT MODIFY THIS FILE! USE docs.platformio.org/page/projectconf/…" I've confirmed also, that when adding references to this file they can get removed
In your user settings add:
this, with the paths provided in another answers, plus ' ** ' appended to the end, did the trick! (ex: "C_Cpp.default.includePath": [ "C:/Users/Administrator/Documents/Arduino/libraries/**" ] )
For myself on Mac I had to be precise about where the header file was, I couldn't encapsulate with a * for the entire folder. For example I had a header file I needed; I had to specify the header folder for VSCode to find it: "C_Cpp.default.includePath":[ "/Users/Github/Learning/Cpp_repo/FreeStore/header/"
This answer maybe late but I just happened to fix the issue. Here is my c_cpp_properties.json file:
The best way to configure the standard headers for your project is by setting the compilerPath property to the configurations in your c_cpp_properties.json file. It is not recommended to add system include paths to the includePath property.
Is there a global c_cpp_properties.json file? I seem to remember there was one, under ~/.vscode/ or perhaps ~/.vscode-oss/ (on linux); now I don't see one.
No, there is no global c_cpp_properties.json file. You can use the C_Cpp.default.* settings to achieve a similar effect though.
I think that this answer uses a confusing expression, perhaps it is just my bad English? I found this much better to understand, copying here @Bob Brown's comment in stackoverflow.com/questions/37522462/…: "In newer versions of the C/C++ extension, it is recommended to use the compilerPath property to set the system includes/defines instead of adding them to the includePath property."
I solved this issue by uninstalling Visual Studio that I had installed recently.
Yes. I had installed Visual Studio over Visual Studio Code which I think did something to VS Code functioning as by simply uninstalling VS, VSCode started running and debugging code.
My c_cpp_properties.json config-
I tried this and now working Configuration for c_cpp_properties.json
task.json configuration File
In the settings, go to c_cpp_properties.json change the settings to:
Okay, I had a similar problem with my VS Code, and here is what I understood, Your C/C++ code runner extension has a default include path value of $/** . This does a recursive top-down search for the library header function files from your workspace folder, this would require you to keep a copy of all your library header function files in all your working folders. I've written below the solution that worked for me.
Step:1This issue can be solved by simply right-clicking on the bulb under the squiggly line (where the error occurs) and click on the "Edit include path settings".
Step:2Now scroll down to the "Include path" section and there add the value of the path to your compiler folder and add /** to enable recursive search in all branching folders. If for any reason you have your library header files stored somewhere else add that path. You could also be more precise by adding the exact value of the folder where the header files are stored.
And that's it! now you should not get that squiggly line error anymore! No more Swiggly Lines!
I'm using an older version of VS Code (1.48.1). This answer solved the problem for me of a file not generating IntelliSense information (same underlying problem as in the question). If resetting the IntelliSense is not enough ( Ctrl+Shift+P → C/C++: Reset IntelliSense database ; it wasn't for me), try this:
You may need to do another reset of the IntelliSense database and restart VS Code before it starts showing all IntelliSense information properly. I also found that it seemed to help to open the include files that it's looking for to help it find the file. I'm hoping this keeps working for me. So far so good.
I am a complete beginner to using Visual Studio Code and I have no clue what I am doing.
I've searched around (maybe not enough), but I can't find just a simple explanation for someone like me on how to configure the c_cpp_properties.json file that I am redirected to whenever I click on the yellow light bulb next to a line that is underlined with a green squiggle.
I just want to know what to put in the .json to make IntelliSense work properly.
3 Answers 3
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.
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
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:
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.
Я новичок в использовании кода Visual Studio, и я понятия не имею, что я делаю.
Я искал (возможно, не достаточно), но я не могу найти просто простое объяснение для кого-то, как я, о том, как настроить c_cpp_properties.json файл, к которому меня перенаправляют всякий раз, когда я нажимаю на желтую лампочку рядом с линией, которая подчеркнута зеленым загогулином.
Я просто хочу знать, что положить в .json заставить IntelliSense работать правильно
Решение
Ниже вы можете видеть, что путь включения MinGW C ++ был добавлен в browse.path для Windows:
Надеюсь, это поможет! 🙂
Другие решения
Из официальной документации расширения C / C ++:
Где определены пути включения?
Пути включения определены в "includePath" установка в файле с именем c_cpp_properties.json находится в каталоге .vscode в открытой папке.
Когда папка открыта, расширение пытается найти системные заголовки на основе вашей операционной системы, но не знает ни о каких других библиотеках, от которых зависит ваш проект. Вы можете навести курсор на зеленые загогулины или открыть окно «Проблемы», чтобы понять, какие заголовки механизм 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. Это позволяет расширению рекурсивно искать в этих папках и предлагать больше предложений в лампочке в процессе поиска.
3. Вручную добавить пути включения
Если ни один из приведенных выше способов полностью не разрешает пути, вы можете вручную указать пути к заголовкам, от которых зависит ваш проект, в c_cpp_properties.json файл. Найдите раздел, в котором определена ваша текущая конфигурация (по умолчанию для каждой ОС существует одна конфигурация, например, «Win32 или« Mac »), и добавьте ваши пути в "includePath" установка и определяет в "defines" установка. Например, на следующем снимке экрана показан фрагмент файла с указанием пути для конфигурации Mac.
Кроме того, для MinGW, как объясняет документация расширения ты можешь спросить GCC / G ++ перечислить свои собственные включаемые файлы:
Убедитесь, что пути включения правильно разрешены
Есть два способа проверить правильность разрешения путей включения:
Это указывает на то, что в движке IntelliSense разрешены пути включения, поэтому вы можете начать пользоваться полным IntelliSense для своего кода C или C ++ для текущего модуля перевода. Обратите внимание, что вы все равно можете видеть ошибки в других файлах, если они принадлежат другому модулю перевода, для которого требуется настроить дополнительные пути включения.
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:
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 "$" it will instruct the extension to read the VS Code default setting for that property and insert it. For example:
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.
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 compileCommands is invalid or the current file is not listed in the database, use the includePath and defines 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 the includePath and defines for the current config already).
- If compilerPath is undefined, look for a compiler on the system and query it.
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.
Читайте также: