Как подключить библиотеку iostream в visual studio code
C++ is a statically-typed general-purpose language middle-level programming language and superset of the C programming language used everywhere but mainly in systems programming and embedded systems. It's also used in making games with the Unreal engine.
In this article, I will show how to set up C++ Compiler with Visual Studio Code. I'm writing this tutorial because I didn't find tutorials with full information in a single place. So here are all the things I have collected from the Internet. I will cover the following things.
Table Of Contents
Prerequisites
- A C++ Compiler (like g++, clang, etc)
- make build tool.
- JSON know-how
- Visual Studio Code (you can get it here)
I will be using Linux Operating System If you are on Windows try this tutorial. For macOS, for the most part, It will be the same excluding the installing compiler part. You can check it here.
Let's get started.
Compiler and Build Tools Installation
I will be using GNU Compiler Collection so to install gcc , g++ , gdb , and make . You can run the following command in the terminal if you using Ubuntu.
Exit fullscreen mode
on Fedora, you can run
Exit fullscreen mode
on Arch-based Linux, you can run
Exit fullscreen mode
Installing VSCode and C++ Extension
Instaling the VSCode is fairly simple, check out this website and check for instructions to install VSCode on your computer.
Once VSCode is installed, open it. You should see the following screen. It may differ because I have changed my theme and have several other extensions.
Now, to install C++ extension goto extensions from the activity bar.
Search for C++ in the search bar and install C/C++ Extension By Microsoft.
Now let's move to set up our project.
Setting Up Project Directory
Having a manageable directory structure is important. It can help you quickly understand where you should look for a file. I opted for the following structure because it is simple.
Exit fullscreen mode
The bin directory will contain the executable after compilation, the include directory will contain all the header files, src will contain all the (as you have guessed) source files.
Setting up Makefile and adding C++ files
Now that we have a directory structure let's write the Makefile . Open VSCode in your project directory. Before that, Let's see what is a Makefile .
Makefile is read by the make utility which executes the tasks defined in Makefile when the files are modified. We will be using it to build our C++ code. You can learn more about Makefile and make here.
For our purposes, following Makefile should work well. so create a Makefile in the root of your project directory. It should spell exactly the same with a capital M.
Exit fullscreen mode
If you want to add additional libraries, you can add it after the LIBRARIES variable. You can also change the name of the executable by changing the EXECUTABLE variable. You can tinker with CXX_FLAGS to change the compiler's behavior (i.e. C++ version) but be sure you don't remove -ggdb flag or you won't be able to debug the program correctly.
After creating the file, our directory structure should look like this:
Exit fullscreen mode
Now that we have our base ready let's add some C++ files. I will create a HelloWorld class that has a say() function that will print out (you guessed it) "Hello, World". Let's create files in our project. I'm gonna use the command line, you can use VSCode or your file manager.
Exit fullscreen mode
Paste the following code in the respective files.
Add following to HelloWorld.hpp .
Exit fullscreen mode
Add following to HelloWorld.cpp .
Exit fullscreen mode
Add following to main.cpp .
Exit fullscreen mode
Testing our setup
Now, we have all our project all set up, we have added some test files. let's test everything out. Open a terminal in the project directory and run make .
Exit fullscreen mode
Now, in the output, we will say the exact command that we would have run if we weren't using make . make has got our back. We don't have to write the whole command each time.
Full explanation of this can be found here.
Setting up VSCode tasks.json
It is still a pain to open a terminal and type make to build our code. We can do better than that. For this, we will be using VSCode's task runner. With this, we can map VSCode's build keyboard shortcut to task by making it of type build . The easiest way to set up tasks is to press ctrl+shift+b . It runs the build task, but as we don't have any yet it will ask us to set up a build task. After pressing the button you should see the following.
Note: If you press the shortcut while a C++ file is open, you will see VSCode's default C++ build tasks. We don't want to use those. So, close the C++ and press the shortcut again
Select 'Configure Build task'
Select 'Create tasks.json from template'
Now, select 'Others'. Now you should see a file created, containing the following content.
Exit fullscreen mode
tasks.json contains all the tasks that VSCode can run for us. In this case, I have created a task that runs a shell command echo Hello by default. Let's change it to make also change the label of the task to better explain the task.
Exit fullscreen mode
I also added a property called group where I define what kind of task it is (i.e. build) and if it's default or not. Setting this is important for the build shortcut to run this task. Now try to build the code with ctrl+shift+b .
Setting up Problem Matcher
Problem matchers scan the task output text for known warning or error strings and report these inline in the editor and in the Problems panel. It supports GCC. So in the tasks.json file add the following in the under the "group" property.
Exit fullscreen mode
Now after running the build task, if any errors or warnings occur you will see them in the problems panel.
Setting up gdb as debugger
We have successfully built our code. Now we are going to configure debugger. To add configuration press F5 , A menu will pop up asking you to choose which debugging solution you want to use. Select 'C/C++' and it will generate launch.json in your project directory containing the following config.
Exit fullscreen mode
We are almost done, here change the "program" property to $/bin/main . Note that if you changed the executable name change main with the name you wrote in the Makefile . Now, press F5 after running the build, make sure the executable was generated, and resides in the path you just wrote in the "program" property.
There is one problem though, you always have to run build before pressing F5 for debugging. But, we can do better add the following in the launch.json after "setupCommands" property.
Exit fullscreen mode
This should run the task we defined before starting the debugger. Press F5 and voilà, Code builds and debugger starts.
I'm hoping this tutorial helped you. If you find any mistake or misinformation please let me know.
Объявляет объекты, управляющие чтением из стандартных потоков и записью в них. Это часто является единственным заголовком, который требуется выполнить в программе C++ для ввода и вывода.
Синтаксис
Комментарии
Объекты можно разделить на две группы:
cin , cout , cerr и clog являются байт-ориентированными, выполняя обычные передачи байтов за раз.
wcin , , wcout wcerr и wclog являются широкими ориентированными, переводя на широкие символы, которые программа управляет внутренне.
После выполнения определенных операций в потоке, таких как стандартные входные данные, нельзя выполнять операции другой ориентации в одном потоке. Таким образом, программа не может работать взаимозаменяемо и cin wcin , например.
Все объекты, объявленные в этом заголовке, имеют своеобразное свойство— можно предположить, что они созданы до определения статических объектов в блоке перевода. Кроме того, можно предположить, что эти объекты не уничтожаются перед деструкторами для любых таких статических объектов, которые вы определяете. (Однако выходные потоки сбрасываются во время завершения программы.) Таким образом, вы можете безопасно считывать данные из стандартных потоков до запуска программы и после завершения программы.
Однако эта гарантия не является универсальной. Статический конструктор может вызвать функцию в другой записи преобразования. Вызываемая функция не может предположить, что объекты, объявленные в этом заголовке, были построены, учитывая неопределенный порядок, в котором единицы перевода участвуют в статической конструкции. Чтобы использовать эти объекты в таком контексте, необходимо сначала создать объект класса ios_base::Init .
Глобальные объекты потоков
Имя | Описание |
---|---|
cerr | Указывает глобальный поток cerr . |
cin | Указывает глобальный поток cin . |
clog | Указывает глобальный поток clog . |
cout | Указывает глобальный поток cout . |
wcerr | Указывает глобальный поток wcerr . |
wcin | Указывает глобальный поток wcin . |
wclog | Указывает глобальный поток wclog . |
wcout | Указывает глобальный поток wcout . |
Объект cerr управляет выходными данными в буфер потока, связанный с объектом stderr , объявленным в .
Возвращаемое значение
Комментарии
Этот объект управляет вставкой без буферизации в стандартный вывод ошибок в виде байтового потока. После создания объекта выражение cerr.flags & unitbuf ненулевое и cerr.tie() == &cout . Дополнительные сведения см. здесь: cerr.flags и unitbuf .
Например, .
Указывает глобальный поток cin .
Возвращаемое значение
Комментарии
Объект контролирует получение данных из стандартного ввода, как потока байтов. После создания объекта вызов cin.tie возвращается &cout .
Например, .
В этом примере задает бит сбоя в потоке, cin когда он встречает нечисловые символы. Программа очищает бит сбоя и удаляет недопустимый символ из потока, чтобы продолжить.
Указывает глобальный поток clog .
Возвращаемое значение
Комментарии
Этот объект управляет вставкой с буферизацей в стандартный вывод ошибок в виде байтового потока.
Например, .
См. cerr с примером использования clog .
Указывает глобальный поток cout .
Возвращаемое значение
Комментарии
Этот объект управляет вставкой в стандартный вывод в виде байтового потока.
Например, .
См. cerr с примером использования cout .
wcerr
Указывает глобальный поток wcerr .
Возвращаемое значение
Комментарии
Этот объект управляет вставкой без буферизации в стандартный вывод ошибок в виде двухбайтового потока. После создания объекта выражение wcerr.flags & unitbuf ненулевое. Дополнительные сведения см. здесь: wcerr.flags и unitbuf .
Например, .
См. cerr с примером использования wcerr .
Указывает глобальный поток wcin .
Возвращаемое значение
Комментарии
Этот объект управляет извлечением из стандартного ввода в виде двухбайтового потока. После создания объекта вызов wcin.tie возвращается &wcout .
Например, .
См. cerr с примером использования wcin .
wclog
Указывает глобальный поток wclog .
Возвращаемое значение
Комментарии
Этот объект управляет вставкой с буферизацей в стандартный вывод ошибок в виде двухбайтового потока.
Например, .
См. cerr с примером использования wclog .
wcout
Указывает глобальный поток wcout .
Возвращаемое значение
Комментарии
Этот объект управляет вставкой в стандартный вывод в качестве широкого потока.
Например, .
См. cerr с примером использования wcout .
Экземпляры CString в операторе wcout необходимо привести к const wchar_t* , как показано в следующем примере.
Обычно программист C++ начинает с создания приложения "Hello, world!", которое запускается из командной строки. Именно его вы и создадите в Visual Studio на этом шаге.
Предварительные требования
- Установите и запустите на своем компьютере Visual Studio с рабочей нагрузкой "Разработка классических приложений на C++". Если установка еще не выполнена, см. статью Установка поддержки C++ в Visual Studio.
Создание проекта приложения
Visual Studio использует проекты, чтобы упорядочить код для приложения, и решения, чтобы упорядочить проекты. Проект содержит все параметры, конфигурации и правила, используемые для сборки приложения. Он управляет связью между всеми файлами проекта и любыми внешними файлами. Чтобы создать приложение, сначала создайте проект и решение.
В Visual Studio откройте меню "Файл" и выберите команду "Создать > Project", чтобы открыть диалоговое окно "Создание нового Project". Выберите шаблон Консольное приложение с тегами C++ , Windows и Консоль, а затем нажмите кнопку Далее.
В диалоговом окне Настроить новый проект в поле Имя проекта введите HelloWorld. Выберите Создать, чтобы создать проект.
Visual Studio создаст проект. Вы можете приступать к добавлению и изменению исходного кода. По умолчанию шаблон консольного приложения добавляет исходный код приложения Hello World:
Когда код в редакторе будет выглядеть таким образом, вы можете перейти к следующему шагу и начать разработку приложения.
В Visual Studio откройте меню "Файл" и выберите команду "Создать > Project", чтобы открыть диалоговое окно "Создать Project".
Visual Studio создаст пустой проект. Вы можете приступать к его настройке в соответствии с типом создаваемого приложения и добавлению файлов исходного кода. Поэтому вы сделаете это сейчас.
Настройка проекта как консольного приложения
Visual Studio позволяет создавать приложения и компоненты самых разных типов как для Windows, так и для других платформ. Шаблон Пустой проект не определяет тип создаваемого приложения. Консольное приложение — это приложение, которое выполняется в консоли или в окне командной строки. Чтобы создать его, необходимо сообщить Visual Studio, что приложение будет использовать подсистему консоли.
Теперь Visual Studio знает, что создаваемый проект предназначен для выполнения в окне консоли. Далее вы добавите файл с исходным кодом и введете код приложения.
Добавление файла исходного кода
В обозревателе решений выберите проект HelloWorld. В меню Проект выберите команду Добавить новый элемент, чтобы открыть диалоговое окно Добавление нового элемента.
Visual Studio создаст пустой файл исходного кода и откроет его в окне редактора, где в него можно ввести код.
Добавление кода в файл исходного кода
Скопируйте код в окне редактора с файлом HelloWorld.cpp.
Код в окне редактора должен выглядеть следующим образом:
Когда код в редакторе будет выглядеть таким образом, вы можете перейти к следующему шагу и начать разработку приложения.
Следующие шаги
Руководство по устранению неполадок
Здесь приведены решения распространенных проблем, которые могут возникнуть при создании первого проекта C++.
Создание проекта приложения: проблемы
В диалоговом окне Новый проект должен быть шаблон Консольное приложение с тегами C++ , Windows и Консоль. Если его нет, возможны две причины. Он может быть отфильтрован из списка или не установлен. Сначала проверьте раскрывающиеся списки фильтров в верхней части списка шаблонов. Выберите фильтры C++ , Windows и Консоль. Должен появиться шаблон консольного приложения C++. Если этого не произошло, значит, рабочая нагрузка Разработка классических приложений на C++ не установлена.
Чтобы установить рабочую нагрузку Разработка классических приложений на C++ , можно запустить установщик прямо из диалогового окна Новый проект. Чтобы запустить установщик, щелкните ссылку Установка других средств и компонентов внизу списка шаблонов. Если в диалоговом окне Контроль учетных записей пользователей запрашиваются разрешения, выберите Да. В установщике должна быть выбрана рабочая нагрузка Разработка классических приложений на C++ . Выберите Изменить, чтобы обновить установку Visual Studio.
Если проект с таким именем уже существует, выберите другое имя для проекта. Можно также удалить существующий проект и повторить попытку. Чтобы удалить существующий проект, удалите папку решения (содержащую файл helloworld.sln) в проводнике.
Если проект с таким именем уже существует, выберите другое имя для проекта. Можно также удалить существующий проект и повторить попытку. Чтобы удалить существующий проект, удалите папку решения (содержащую файл helloworld.sln) в проводнике.
Настройка проекта как консольного приложения: проблемы
Раскрывающийся список не открывается в поле свойства Подсистема, пока не будет выбрано свойство. Щелкните поле ввода, чтобы выбрать его. Можно также последовательно переходить по элементам управления в диалоговом окне с помощью клавиши TAB, пока не будет выделено поле Подсистема. Щелкните раскрывающийся список или нажмите клавиши ALT+стрелка вниз, чтобы открыть его.
Добавление файла исходного кода: проблемы
Файлу исходного кода можно спокойно присвоить другое имя. Однако не добавляйте в проект несколько файлов с одинаковым кодом.
Если вы добавили в проект файл неправильного типа, например файл заголовка, удалите его и повторите попытку. Чтобы удалить файл, выберите его в обозревателе решений. Затем нажмите клавишу DELETE.
Добавление кода в файл исходного кода: проблемы
Если вы случайно закрыли окно редактора с файлом исходного кода, его можно легко открыть снова. Чтобы сделать это, дважды щелкните файл HelloWorld.cpp в окне обозревателя решений.
Если в редакторе исходного кода какие-либо элементы подчеркнуты красной волнистой линией, проверьте, соответствуют ли их написание, пунктуация и регистр символов используемым в примере. В коде на C++ регистр имеет важное значение.
Для разработки программ на языке c++ вы можете использовать среду разработки Visual Studio Code (VSCode).
Сегодня мы рассмотрим установку поддержки языка программирования с++ в этой IDE.
Выбор компилятора
Перед установкой расширения для поддержки с++ в VSCode нам нужно сначала определиться какой компилятор использовать.
Под Windows существует несколько возможностей:
- Вы можете использовать Windows Subsystem for Linux (WSL) и установив в виртуальной машине все необходимые пакеты компилировать программы с помощью специального расширения для VSCode.
- Вы можете установить MinGW или MSYS2 и использовать их компиляторы.
- Вы можете установить компилятор Microsoft C++ compiler (MSVC)
Сегодня мы рассмотрим самый простой способ – установку Microsoft C++ compiler (MSVC).
Установка Microsoft C++ compiler (MSVC)
Для начала скачаем установщик по ссылке:
Скачиваем файл, в моем случае он называется:
Запускаем, откроется окно:
Будет запущена консоль разработчика:
Компилятор успешно установлен и доступен.
Теперь пришло время установить расширение для поддержки с++ в VSCode.
Установка расширения для поддержки С++ в VSCode
Откроется панель Extensions: Marketplace – это каталог, из которого мы можем скачать все необходимые расширения и темы, достаточно знать их название.
Выберите указанный пункт и нажмите install
Будет начато скачивание дополнительных компонентов. После окончания загрузок расширение будет готово к использованию.
Настройка VSCode для использования компилятора MSVC
Для того, чтобы протестировать работу компилятора создадим тестовый проект.
Для нормального функционирования компилятора MSVC нужно установить несколько переменных окружения. Чтобы упростить задачу воспользуемся Visual Studio 2019 Developer Command Prompt.
Запустите его из меню Пуск введя слово developer, откроется консоль:
Создадим данную папку и перейдем в нее:
Создадим папку для проекта test
Запустим VSCode из этой папки
Откроется окно VSCode
Обратите внимание наша папка уже открыта.
Добавим новый файл для этого нажмите на кнопку:
Настройка компилятора для проекта
Теперь у нас есть программа, осталось её скомпилировать, давайте настроим задачу сборки для проекта.
using namespace std;
int main()
string firstName, lastName;
double hourRate, numHours;
My c_cpp_properties.json file
Let me know if you need any more information
The text was updated successfully, but these errors were encountered:
GiBg1aN commented Sep 19, 2017
If you are using Linux you have to add the path /usr/include/linux
ZoeVonFeng commented Sep 20, 2017 •
I had same issue on windows, after I add the "C:\\cygwin64\\lib\\gcc\\x86_64-pc-cygwin\\6.4.0\\include\\c++" at includePath, I got this error: cannot open source file "bits/c++config.h" (dependency of "iostream")
bobbrow commented Sep 20, 2017 •
What does gcc tell you the include path should be? Run this command and make sure all of the paths printed out are listed in your c_cpp_properties.json: gcc -v -E -x c++ -
NikoGP commented Sep 20, 2017
sean-mcmanus commented Sep 20, 2017
@NikoGP Go to File->Preferences->Settings and search for "intelliSenseEngine" to find the setting. You have "Default" set already though. Did you run the gcc command @bobbrow mentioned? Can you provide your updated c_cpp_properties.json? You basically need to find where your iostream header is getting pulled from by your compiler and add the path to the includePath setting (and make sure the defines are correct). Does Go to Definition work on the header file? If so, that means the iostream file was found via a recursive search of your browse.path setting.
NikoGP commented Sep 20, 2017 •
Here is my current c_cpp_properties.json file, when I hover over the " Also, I installed cygwin before installing MingW, I'm not sure if that messes anything up or not
bobbrow commented Sep 20, 2017
I reformatted your comment. There is a "configurations" element inside your "configurations" which is invalid syntax for the c_cpp_properties.json file. Fix it like below:
NikoGP commented Sep 20, 2017
bobbrow commented Sep 20, 2017 •
What version of MinGW are you using? In your first post, it looked like you had 6.3.0 in your include path. In your most recent post, it looked like you pasted in include paths for 5.3.0 from our MinGW page.
NikoGP commented Sep 20, 2017
Okay, I think that my problem lies in the fact that I had installed cygwin prior to MingW, and then I incorrectly installed the required packages for MingW to properly function.
Is there somewhere that I can find what packages I need to install for VS Code to work properly with MingW?
smithalexk commented Sep 27, 2017
I am also having the issue seen by @NikoGP with my Intellisense after upgrading to v0.13.0. When I turned on the "Default" setting on the Intellisense engine, I keep receiving an iostream include path error (see attached files). I'm running MacOS 10.12.6, and have updated the LLVM engine as well.
Simple "Hello World" example showing the error:
My c_pp_properties.json file:
bobbrow commented Sep 27, 2017
@smithalexk, for me, this file resides in /usr/include . What does clang -Wp,-v -E -xc -x c++ /dev/null show as your include path? The "includePath" in your c_cpp_properties.json file should match that.
smithalexk commented Sep 27, 2017
Yep that looks to have fixed it. Thanks for the help!
For reference, I was missing:
/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.13.sdk/usr/include
/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.13.sdk/System/Library/Frameworks
dorsa1986 commented Sep 29, 2017
my c_cpp_properties.json file:
My tasks.json file:
My launch.json file:
My User Setting is:
The path of the FirstProg folder is :
bobbrow commented Oct 2, 2017
@dorsa1986, what does g++ -Wp,-v -E -xc -x c++ /dev/null show as your include path? The "includePath" in your c_cpp_properties.json file should match that.
smithalexk commented Oct 2, 2017
Hi @dorsa1986, I also noticed that you spelled "iostream" incorrectly. You are currently including the "ioastream" header. That looks like it could be causing your error.
dorsa1986 commented Oct 2, 2017
@smithalexk Thanks, I corrected but still, I got error
dorsa1986 commented Oct 2, 2017
bobbrow commented Oct 2, 2017
According to that error, either your tasks.json is not building your program correctly, or your launch.json has an incorrect path to the built program. But this is not an issue with IntelliSense. I don't see any red squiggles in your editor.
dorsa1986 commented Oct 2, 2017
how can I solve them?
bobbrow commented Oct 2, 2017
Open tasks.json or launch.json (in the .vscode folder) and verify that they are correct
dorsa1986 commented Oct 2, 2017
it's my launch.jason file:
dorsa1986 commented Oct 2, 2017
This is my tasks.json:
I've been working on this about 4 days. I can't find my mistake.
bobbrow commented Oct 2, 2017
Based on what I see in your previous posts, I'm going to guess that the path should be /Users/dorsat/Desktop/FirstProg/a.out
dorsa1986 commented Oct 2, 2017
I got the same error.
bobbrow commented Oct 2, 2017
Did you build it yet? Open your terminal or a Finder window and tell me where your compiled program lives.
sean-mcmanus commented Oct 2, 2017 •
@dorsa1986 Is a.out the name of the executable? Does it have executable permissions? Can you run it without VS Code from a command line?
bobbrow commented Oct 2, 2017
There should be plenty of websites out there that can walk you through the steps of getting your code to build. This forum is for troubleshooting bugs in the VS Code Extension and your issue doesn't appear to be a bug since it doesn't appear to work for you in the terminal either.
I'm running out of ideas for you, but these came to mind:
- Check your filesystem to make sure the headers are there (look at the include paths that your compiler tells you it's using)
- Did you install XCode, or run xcode-select --install?
- Did you install a different compiler you can try? (your tasks.json references g++, but your terminal screenshots show cpp)
- It looks like you have an a.out in your folder already. How did you get it?
perryizgr8 commented Oct 10, 2017
I have followed all the suggestions in this thread and now my browse.path and includePath are same as the entries found using "g++ -Wp,-v -E -xc -x c++ /dev/null".
However, I still cannot include iostream or atomic or stdio, basically any standard header. My own headers from a sub-directory are fine.
To be clear, mine is not a build issue (I'm using my own build system), but an intellisense issue. A peculiarity is that my code resides on a remote Ubuntu server, and I am running VS code on my Windows laptop with the Z: drive mounted to / on the server. I'd be grateful if anybody has any ideas.
bobbrow commented Oct 10, 2017
Can you share the include path given by g++? Is it the path on the Ubuntu server or the mapped location on Windows? The includePath needs to match the filesystem of the OS you're working on (in this case Windows with the Z: path).
perryizgr8 commented Oct 10, 2017
This is the output of the g++ command on the Ubuntu machine:
I have / mounted to drive letter Z, so my includePath looks like this:
As you can see, I have translated each path to the equivalent path on my Windows system. I can access the headers using these paths in Windows Explorer, so the path is correct. So even though I can open the iostream header by navigating to "z:\usr\include\x86_64-linux-gnu\c++\5" and opening the file in any editor, VS code still shows a green squiggle below its include.
I am accessing the server over the internet, so I'm worried this might have something to do with VS code being unable to parse files that are slow to read. Is that likely to cause this problem? The fire icon in the bottom right does go away after a while (1-2 min).
Читайте также: