Как изменить include path vs code

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.

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:

  1. 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):
      1. If systemIncludePath has a value, use it (continue to the next step to search for system defines).
      2. If compilerPath is valid, query it.
      3. Interpret the first argument in the command as the compiler and attempt to query it.
      4. If compilerPath is «», use an empty array for system include path and defines.
      5. If compilerPath is undefined, look for a compiler on the system and query it.
  2. 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):
      1. If systemIncludePath has a value, use it (continue to the next step to search for system defines).
      2. If compilerPath is valid, query it.
      3. 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).
      4. 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.

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.

Configure includePath for better IntelliSense

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.

lightbulb menu "Edit "includePath" setting"

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.

include error message

How can I specify the include paths?

You can specify the remaining paths using one of the techniques described below.

  1. 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 compileCommands setting

  2. 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.

    lightbulb suggestions

    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.

  3. 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
    

    c_cpp_properties file snippet

Verify the include paths are correctly resolved

There are two ways to verify that the include paths are correctly resolved:

  1. The green squiggles in the source file are no longer showing
  2. 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:

  1. 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):
      1. If systemIncludePath has a value, use it (continue to the next step to search for system defines).
      2. If compilerPath is valid, query it.
      3. Interpret the first argument in the command as the compiler and attempt to query it.
      4. If compilerPath is «», use an empty array for system include path and defines.
      5. If compilerPath is undefined, look for a compiler on the system and query it.
  2. 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):
      1. If systemIncludePath has a value, use it (continue to the next step to search for system defines).
      2. If compilerPath is valid, query it.
      3. 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).
      4. 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.

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

JSON
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
{
    "configurations": [
        {
            "name": "Win32",
            "includePath": [
                "${workspaceFolder}/**",
                "C:\MinGW\lib\gcc\mingw32\9.2.0\include\c++"
            ],
            "defines": [
                "_DEBUG",
                "UNICODE",
                "_UNICODE"
            ],
            "compilerPath": "C:\MinGW\bin\gcc.exe",
            "cStandard": "c11",
            "cppStandard": "gnu++14",
            "intelliSenseMode": "gcc-x86",
            "browse": {
                "path": []
            }
        }
    ],
    "version": 4
}

launch.json

JSON
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
  "version": "0.2.0",
    "configurations": [
        {
            "name": "g++.exe - Сборка и отладка активного файла",
            "type": "cppdbg",
            "request": "launch",
            "program": "${fileDirname}\${fileBasenameNoExtension}.exe",
            "args": [],
            "stopAtEntry": false,
            "cwd": "${workspaceFolder}",
            "environment": [],
            "externalConsole": false,
            "MIMode": "gdb",
            "miDebuggerPath": "C:\MinGW\bin\gdb.exe",
            "setupCommands": [
                {
                    "description": "Включить автоматическое форматирование для gdb",
                    "text": "-enable-pretty-printing",
                    "ignoreFailures": true
                }
            ],
            "preLaunchTask": "C/C++: g++.exe build active file"
        }
    ]
}

tasks.json

JSON
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
{
    "version": "2.0.0",
    "tasks": [
        {
            "type": "shell",
            "label": "C/C++: g++.exe build active file",
            "command": "C:\MinGW\bin\g++.exe",
            "args": [
                "-g",
                "${file}",
                "-o",
                "${fileDirname}\${fileBasenameNoExtension}.exe"
            ],
            "options": {
                "cwd": "C:\MinGW\bin"
            },
            "problemMatcher": [
                "$gcc"
            ],
            "group": {
                "kind": "build",
                "isDefault": true
            }
        }
    ]
}

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



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

Цитата
Сообщение от P1XELCORE
Посмотреть сообщение

Обнаружены ошибки #include. Измените includePath», что он хочет от меня?

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

Цитата
Сообщение от P1XELCORE
Посмотреть сообщение

«includePath»: [
«${workspaceFolder}/**»,
«C:\MinGW\lib\gcc\mingw32\9.2.0\include\c++ «
],

Проверь наличие таких директорий, либо поправь пути если они в другом месте.



0



0 / 0 / 0

Регистрация: 11.04.2013

Сообщений: 78

11.08.2020, 13:15

 [ТС]

3

Цитата
Сообщение от assemberist
Посмотреть сообщение

Проверь наличие таких директорий, либо поправь пути если они в другом месте.

я сам прописал этот путь, было бы странно если бы там не было этих директорий)
изначально там не было пути, поэтому я решил что стоит в includPath ещё и путь прописать поэтому так и сделал, но это не решило моей проблемы



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

Цитата
Сообщение от Алексей1153
Посмотреть сообщение

звёзды вроде не к месту ?

Они по дефолту стояли в этом файле. Как я понял не просто так, т.к. про них написано в справочнике «Если путь заканчивается на /**, подсистема IntelliSense будет выполнять рекурсивный поиск файлов заголовков, начиная с этого каталога.»

Цитата
Сообщение от Алексей1153
Посмотреть сообщение

редактируй эти настройки через визард, тогда будет меньше ошибок

не совсем понимаю что значит редактировать через визард)



0



фрилансер

4479 / 3989 / 870

Регистрация: 11.10.2019

Сообщений: 10,507

11.08.2020, 14:19

6

Цитата
Сообщение от P1XELCORE
Посмотреть сообщение

через визард

то есть, напрямую файл править не надо, надо открывать свойства проекта — зависимости, пути и т.д. Там же можно посмотреть, во что раскрываются макросы вида ${…}

Добавлено через 1 минуту

Цитата
Сообщение от P1XELCORE
Посмотреть сообщение

«Обнаружены ошибки #include. Измените includePath»,

а покажи скрин, кстати



1



0 / 0 / 0

Регистрация: 11.04.2013

Сообщений: 78

11.08.2020, 14:58

 [ТС]

7

Цитата
Сообщение от Алексей1153
Посмотреть сообщение

а покажи скрин, кстати

Ошибка include, измените includePath в VS code



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, там по логике прописываются пути для компилятора и библиотек

Ошибка include, измените includePath в VS code



0



0 / 0 / 0

Регистрация: 11.04.2013

Сообщений: 78

11.08.2020, 15:09

 [ТС]

10

Цитата
Сообщение от Алексей1153
Посмотреть сообщение

P1XELCORE, iostream
и настройки тут ни при чём

действительно, спасибо огромное) запустилось!

только теперь ругается консоль отладки, но всё же спасибо)



0



фрилансер

4479 / 3989 / 870

Регистрация: 11.10.2019

Сообщений: 10,507

11.08.2020, 19:31

11

Цитата
Сообщение от P1XELCORE
Посмотреть сообщение

теперь ругается консоль отладки

как ругается ?



0



0 / 0 / 0

Регистрация: 11.04.2013

Сообщений: 78

12.08.2020, 08:46

 [ТС]

12

Цитата
Сообщение от Алексей1153
Посмотреть сообщение

как ругается ?

Ошибка include, измените includePath в VS code

вот эти строки о том что какие-то символы загружены, они так и должны быть? мне кажется в окно вывода должно просто хеллоу ворд выходить)
а если например написать программу где нужно вводить входные данные, то она отладку не проходит вовсе



0



фрилансер

4479 / 3989 / 870

Регистрация: 11.10.2019

Сообщений: 10,507

12.08.2020, 09:05

13

P1XELCORE, так и смотри в окне вывода. У тебя всё там не на английском, но предполагаю, это вкладка «выходные данные»

а может и «терминал». Или вообще окно в настройках не включено

Добавлено через 3 минуты
так вон, вроде, текст то вывелся синеньким. Только всякий мусор вокруг. Да и код выхода 0 вижу



0



406 / 290 / 119

Регистрация: 18.07.2017

Сообщений: 1,346

12.08.2020, 09:41

14

Цитата
Сообщение от P1XELCORE
Посмотреть сообщение

какие-то символы загружены

Судя по всему это загрузка метаданных для дебаггера из модулей, которые будут использоваться твоей программой.

Цитата
Сообщение от P1XELCORE
Посмотреть сообщение

мне кажется в окно вывода должно просто хеллоу ворд выходить

А мне кажеся, что дебаггеру плевать на ввод-вывод, если не поставлена точка останова. Если у этой консоли та же логика что и в gdb, то туда нужно вводить название переменных либо выражения. И дебаггер покажет значение переменной, либо рассчитает выражение.

Цитата
Сообщение от P1XELCORE
Посмотреть сообщение

программу где нужно вводить входные данные, то она отладку не проходит вовсе

Всмысле не проходит? Зависает? Ну так может нужно данные вводить не в консоль отладки, а в окно самой программы? У тебя там консолька не всплывает случаем на фоне?



0



0 / 0 / 0

Регистрация: 11.04.2013

Сообщений: 78

12.08.2020, 10:21

 [ТС]

15

Цитата
Сообщение от Алексей1153
Посмотреть сообщение

но предполагаю, это вкладка «выходные данные»
а может и «терминал». Или вообще окно в настройках не включено

Во вкладке «выходные данные» пусто всегда, а в терминале вот такое выходит когда без проблем компилируется

Миниатюры

Ошибка include, измените includePath в VS code
 

Ошибка include, измените includePath в VS code
 



0



0 / 0 / 0

Регистрация: 11.04.2013

Сообщений: 78

12.08.2020, 10:25

 [ТС]

16

Цитата
Сообщение от assemberist
Посмотреть сообщение

Всмысле не проходит? Зависает? Ну так может нужно данные вводить не в консоль отладки, а в окно самой программы? У тебя там консолька не всплывает случаем на фоне?

Консолька не всплывает для ввода данных, просто опять что-то пишет в консоль отладки и в терминал

Миниатюры

Ошибка include, измените includePath в VS code
 

Ошибка include, измените includePath в VS code
 



0



Алексей1153

фрилансер

4479 / 3989 / 870

Регистрация: 11.10.2019

Сообщений: 10,507

12.08.2020, 10:46

17

P1XELCORE, кстати, да, у тебя приложение то консольное? Тогда консоль должна быть на экране. А в окно отладки, которое снизу, вывод в студии производится через TRACE/TRACE0/OutputDebugString (понадобится заголовок <Windows.h> )

Добавлено через 2 минуты
ещё, говорят, так можно показать/скрыть (тоже тот же заголовок нужен)

C++
1
2
ShowWindow (GetConsoleWindow(), SW_SHOW);
ShowWindow (GetConsoleWindow(), SW_HIDE);



0



406 / 290 / 119

Регистрация: 18.07.2017

Сообщений: 1,346

12.08.2020, 10:53

18

Цитата
Сообщение от P1XELCORE
Посмотреть сообщение

просто опять что-то пишет в консоль отладки и в терминал

Ну ок, а почему точку останова до сих пор не поставил? Как у тебя дебаггер будет стопать программу?



0



0 / 0 / 0

Регистрация: 11.04.2013

Сообщений: 78

12.08.2020, 11:06

 [ТС]

19

Цитата
Сообщение от assemberist
Посмотреть сообщение

Ну ок, а почему точку останова до сих пор не поставил? Как у тебя дебаггер будет стопать программу?

Поставил) всё так же)

Миниатюры

Ошибка include, измените includePath в VS code
 



0



0 / 0 / 0

Регистрация: 11.04.2013

Сообщений: 78

12.08.2020, 11:09

 [ТС]

20

Цитата
Сообщение от Алексей1153
Посмотреть сообщение

кстати, да, у тебя приложение то консольное?

ну, если консолька не выходит при запуске программы, значит не консольное?)
я попробовал добавил в код то что вы написали, всё так же)



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 для лучшего IntelliSense

Где определены пути включения?

Пути включения определены в "includePath" установка в файле с именем c_cpp_properties.json находится в каталоге .vscode в открытой папке.

Вы можете создать или открыть этот файл, используя "C/Cpp: Edit Configurations" Команда в палитре команд или выбрав "Edit "includePath" setting" в меню лампочки (см. скриншот ниже). Самый быстрый способ найти лампочку — это прокрутить верхнюю часть исходного файла и щелкнуть на любой зеленой загадке, которая появляется под оператором #include.

меню лампочки «Редактировать» включает в себя «путь» установка & Quot;

Когда папка открыта, расширение пытается найти системные заголовки на основе вашей операционной системы, но не знает ни о каких других библиотеках, от которых зависит ваш проект. Вы можете навести курсор на зеленые загогулины или открыть окно «Проблемы», чтобы понять, какие заголовки механизм 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.

использовать параметр compileCommands

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

Фрагмент файла c_cpp_properties

Убедитесь, что пути включения правильно разрешены

Есть два способа проверить правильность разрешения путей включения:

  1. Зеленые загогулины в исходном файле больше не отображаются
  2. Сообщения об ошибках очищаются в окне «Проблемы».

Это указывает на то, что в движке 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"

Понравилась статья? Поделить с друзьями:
  • Как изменить implicit poe
  • Как изменить img на pdf на айфоне
  • Как изменить img на bin
  • Как изменить imei модема huawei e173
  • Как изменить img src js