Ошибка iostream file not found

I wrote the following simple C++ program:

#include <iostream>

using namespace std;

int main() {
    cout << "Hello, World" << endl;
    return 0;
}

When I compile this with g++, it works perfectly. When I try to compile with Clang++, I get the following error:

main.cpp:1:10: fatal error: 'iostream' file not found
#include <iostream>
         ^~~~~~~~~~
1 error generated.

Running with the -v parameter, I see the following:

ignoring nonexistent directory "/usr/bin/../lib/gcc/x86_64-linux-gnu/8/../../../../include/c++/x86_64-linux-gnu"
ignoring nonexistent directory "/usr/bin/../lib/gcc/x86_64-linux-gnu/8/../../../../include/c++/backward"
ignoring nonexistent directory "/include"
ignoring duplicate directory "/usr/include/clang/6.0.0/include"
#include "..." search starts here:
#include <...> search starts here:
 /usr/bin/../lib/gcc/x86_64-linux-gnu/8/../../../../include/c++
 /usr/include/clang/6.0.0/include
 /usr/local/include
 /usr/include/x86_64-linux-gnu
 /usr/include
End of search list.

Looking into these folders individually, I found that in /usr/bin/../lib/gcc/x86_64-linux-gnu/8/../../../../include/c++ (or, more concisely, in /usr/include/c++) I have the following directories:

drwxr-xr-x   5 root root 4.0K Feb  4 09:38 .
drwxr-xr-x 101 root root  20K Feb  4 12:22 ..
drwxr-xr-x  12 root root  12K May 24  2018 5
drwxr-xr-x  12 root root  12K Oct  9 14:53 7
drwxr-xr-x   5 root root 4.0K Feb  4 09:38 v1
lrwxrwxrwx   1 root root    1 Apr 11  2018 5.5.0 -> 5
lrwxrwxrwx   1 root root    1 Apr 15  2018 7.3.0 -> 7

Within each of the 5, 7, and v1 directories there exists a file called iostream

Also in /usr/include/x86_64-linux-gnu there exists a c++ directory which looks exactly like this one (with 5, 7, 5.5.0, and 7.3.0 directories).

Also in /usr/include there exists a c++ directory which looks exactly like the two above

I’m not sure how my dev environment became such a mess, but at this point I would just like to know how to fix it so that Clang++ will successfully find one of these 9 instances of iostream instead of throwing an error that it doesn’t exist. Do I need to add an environment variable to tell Clang where to look? Do I need to pass a command-line parameter to tell Clang to search recursively?

Update (1)

When I try building with libc++ I get the following error:

$> clang++ -stdlib=libc++ main.cpp
/usr/bin/ld: cannot find -lc++abi
clang: error: linker command failed with exit code 1 (use -v to see invocation)

When I try building with the include path manually overridden, I get the following error:

$> clang++ -isystem /usr/include/c++/7 -isystem /usr/include/x86_64-linux-gnu/c++/7 main.cpp
/usr/bin/ld: cannot find -lstdc++
clang: error: linker command failed with exit code 1 (use -v to see invocation)

When I try both, I get the following (incredibly large) error:

$> clang++ -isystem /usr/include/c++/7 -isystem /usr/include/x86_64-linux-gnu/c++/7 -stdlib=libc++ main.cpp
In file included from main.cpp:1:
In file included from /usr/include/c++/7/iostream:39:
In file included from /usr/include/c++/7/ostream:38:
In file included from /usr/include/c++/7/ios:42:
In file included from /usr/include/c++/7/bits/ios_base.h:41:
In file included from /usr/include/c++/7/bits/locale_classes.h:40:
In file included from /usr/include/c++/7/string:52:
In file included from /usr/include/c++/7/bits/basic_string.h:6352:
In file included from /usr/include/c++/7/ext/string_conversions.h:41:
In file included from /usr/include/c++/7/cstdlib:77:
/usr/include/c++/7/bits/std_abs.h:56:3: error: declaration conflicts with target of using declaration already in scope
  abs(long __i) { return __builtin_labs(__i); }
  ^
/usr/include/c++/v1/stdlib.h:111:44: note: target of using declaration
inline _LIBCPP_INLINE_VISIBILITY long      abs(     long __x) _NOEXCEPT {return  labs(__x);}
                                           ^
/usr/include/c++/7/bits/std_abs.h:52:11: note: using declaration
  using ::abs;
          ^
/usr/include/c++/7/bits/std_abs.h:61:3: error: declaration conflicts with target of using declaration already in scope
  abs(long long __x) { return __builtin_llabs (__x); }
  ^
/usr/include/c++/v1/stdlib.h:113:44: note: target of using declaration
inline _LIBCPP_INLINE_VISIBILITY long long abs(long long __x) _NOEXCEPT {return llabs(__x);}
                                           ^
/usr/include/c++/7/bits/std_abs.h:52:11: note: using declaration
  using ::abs;
          ^
In file included from main.cpp:1:
In file included from /usr/include/c++/7/iostream:39:
In file included from /usr/include/c++/7/ostream:38:
In file included from /usr/include/c++/7/ios:42:
In file included from /usr/include/c++/7/bits/ios_base.h:41:
In file included from /usr/include/c++/7/bits/locale_classes.h:40:
In file included from /usr/include/c++/7/string:52:
In file included from /usr/include/c++/7/bits/basic_string.h:6352:
In file included from /usr/include/c++/7/ext/string_conversions.h:41:
/usr/include/c++/7/cstdlib:177:3: error: declaration conflicts with target of using declaration already in scope
  div(long __i, long __j) { return ldiv(__i, __j); }
  ^
/usr/include/c++/v1/stdlib.h:116:42: note: target of using declaration
inline _LIBCPP_INLINE_VISIBILITY  ldiv_t div(     long __x,      long __y) _NOEXCEPT {return  ldiv(__x, __y);}
                                         ^
/usr/include/c++/7/cstdlib:145:11: note: using declaration
  using ::div;
          ^

As a reminder, I’m literally just trying to compile Hello, World

I also tried uninstalling and re-installing Clang with the following command:

$> sudo apt-get purge --auto-remove clang
$> sudo apt-get update
$> sudo apt-get install clang

This had no effect. I’m running Ubuntu 18.04 and I have no idea what’s wrong or where to start with fixing it. My build environment is in shambles.

If possible I would like to get Clang working instead of falling back to using G++, because my IDE seems to be automatically detecting Clang and using it for syntax checking. This means that every C++ program I’ve written has one fatal error on line one («iostream not found») and the rest of the file goes unchecked because that first one is a fatal error.

Update (2)

I’ve tried installing a few more packages from the Ubuntu apt repository with no luck:

$> sudo apt-get install libc++1 libc++1-9 libc++abi1 libc++abi1-9 llvm-9 llvm-9-dev
$> clang++ -isystem /usr/include/c++/7 -isystem /usr/include/x86_64-linux-gnu/c++/7 -stdlib=libc++ main.cpp
/usr/bin/ld: cannot find -lc++
clang: error: linker command failed with exit code 1 (use -v to see invocation)

I also tried sudo apt-get install lc++1 only to find this is an entirely unrelated package.

Update (3)

I spent several more hours trying to resolve this, installing multiple packages both from apt and from source, trying different versions of various tools, manually copying in libraries from other sources, and even hopped onto the Clang IRC and spoke to several very knowledgeable developers directly.

No one was able to figure out what’s wrong with my laptop, and nothing I did ever got it working.

Unfortunately I won’t still have this laptop in another two weeks, so I’ll likely need to close this issue as «cannot reproduce» — because once the laptop is gone I will have no way of replicating the broken development environment.

After upgrade to 14.04 from 12.04 clang++ stopped working.

$ cat test.cpp 
#include <iostream>

int main()
{
        std::cout << "Hello World" << std::endl;
        return 0;
}

$ clang++ test.cpp 
test.cpp:1:10: fatal error: 'iostream' file not found
#include <iostream>
         ^
1 error generated

Installed with apt-get install clag-3.5 same happened with clang-3.4

Thanks

asked Aug 27, 2014 at 16:37

Artyom's user avatar

4

I found to resolve this issue that after installing libstdc++-4.8-dev package, I need to specify the include paths and lib path to the clang++ like this.

clang++ -I/usr/include/c++/4.8/ -I/usr/include/x86_64-linux-gnu/c++/4.8 -L /usr/lib/gcc/x86_64-linux-gnu/4.8 test.cpp -o test

Marc Vanhoomissen's user avatar

answered Jan 2, 2018 at 16:02

Sanya Phungmit's user avatar

1

Your code works for me. Make sure you have libstdc++-dev installed. It’s a virtual package, and in my case (Ubuntu 14.04.2 LTS) having 4.8 works.

sudo apt-get install libstdc++-4.8-dev

answered May 18, 2015 at 20:07

m0j0's user avatar

m0j0m0j0

1356 bronze badges

2

@ZoeGM1997

I was trying to use clangd in VSCode in my project. But clangd could not find the iostream file.

Error report:
‘iostream’ file not foundclang(pp_file_not_found)

clangd 11.0.0
Win 10

@sam-mccall

Clangd doesn’t provide a standard library, and expects to use one already installed on your system. This may require configuring with some flags, as if you were building with clang.

But we realize this is probably confusing/a hassle, particularly for windows users. Maybe we should bundle the headers. Can I ask:

  • do you also expect to build your project on the machine clangd is running on?
  • do you have a C++ compiler installed (e.g. MSVC, clang, gcc)

@ZoeGM1997

Thanks for @sam-mccall commend.

  1. Yes, I expect my project would be builded with clangd running on
  2. I’ve installed clang-x64 (no MSVC) and MinGW 64

I added INCLUDE into environment variable with value: «C:mingw64libgccx86_64-w64-mingw328.1.0includec++». That could direct VSCode where iostream file is. However another bug appears that VScode could not find other header files like «c++config.h». It seems like all subdirectories could not be searched. That’s really confusing.

Here is the c_cpp_properties.json
image

@InsaneZulol

So how and where do I specify the flags so my clangd sees standard library? Somewhere in settings.json? Or CMakeLists.txt so cmake generates compilation_commands with stdlib location specified? I’m a confused windows user.

image

@TamaMcGlinn

clangd —help says:

  --enable-config                 - Read user and project configuration from YAML files.
                                    Project config is from a .clangd file in the project directory.
                                    User config is from clangd/config.yaml in the following directories:
                                        Windows: %USERPROFILE%AppDataLocal
                                        Mac OS: ~/Library/Preferences/
                                        Others: $XDG_CONFIG_HOME, usually ~/.config
                                    Configuration is documented at https://clangd.llvm.org/config.html

So hopefully your answer is here.

@notox

Thanks for @sam-mccall commend.

  1. Yes, I expect my project would be builded with clangd running on
  2. I’ve installed clang-x64 (no MSVC) and MinGW 64

I added INCLUDE into environment variable with value: «C:mingw64libgccx86_64-w64-mingw328.1.0includec++». That could direct VSCode where iostream file is. However another bug appears that VScode could not find other header files like «c++config.h». It seems like all subdirectories could not be searched. That’s really confusing.

Here is the c_cpp_properties.json
image

I meet the same problem. Do you have resolved your problem?

@InsaneZulol

No sorry, I didn’t really have time to figure it out as I wanted to have a working indexing asap for work. It was challenging to set it up without sudo on rhel.
I did provide correct compile_commands.json that ccls has no problems with — but clangd just bugged out every single time on it.
I think it was a bug with a clagd9 iirc.
If it’s also a pressing matter for you try out @MaskRay ccls. It’s even better than clangd especially in ssh environment.

@kadircet

@ZoeGM1997 and @notox

sorry for losing track here. but clangd doesn’t read any configuration specific to an editor (vscode in this case) as it needs to be working with multiple editors. so instead it reads compile flags through compile_commands.json or compile_flags.txt that can be generated by hand or by the build system.

in case of a mingw toolchain, making sure your flags have the correct target set (e.g. -target x86_64-pc-windows-gnu) usually gets the job done.

@notox

@ZoeGM1997 and @notox

sorry for losing track here. but clangd doesn’t read any configuration specific to an editor (vscode in this case) as it needs to be working with multiple editors. so instead it reads compile flags through compile_commands.json or compile_flags.txt that can be generated by hand or by the build system.

in case of a mingw toolchain, making sure your flags have the correct target set (e.g. -target x86_64-pc-windows-gnu) usually gets the job done.

-target x86_64-pc-windows-gnu is worked. Thank you for your help.

I used CMake to generate compile_commands.json. I’m new to use CMake and don’t know how to set the target in CMakeLists.txt. Do you know that?


1 similar comment

@notox

@ZoeGM1997 and @notox

sorry for losing track here. but clangd doesn’t read any configuration specific to an editor (vscode in this case) as it needs to be working with multiple editors. so instead it reads compile flags through compile_commands.json or compile_flags.txt that can be generated by hand or by the build system.

in case of a mingw toolchain, making sure your flags have the correct target set (e.g. -target x86_64-pc-windows-gnu) usually gets the job done.

-target x86_64-pc-windows-gnu is worked. Thank you for your help.

I used CMake to generate compile_commands.json. I’m new to use CMake and don’t know how to set the target in CMakeLists.txt. Do you know that?

@BharatSahlot

I used CMake to generate compile_commands.json. I’m new to use CMake and don’t know how to set the target in CMakeLists.txt. Do you know that?

@notox Did you find a way to do it? I tried adding -target x86_64-pc-windows-gnu to my config file, but it does not work.

@7xRone

i don’t understand why would you close this issue while it still not solved after 2 years
im really disappointed.

@PIesPnuema

I know it is not windows but I was able to resolve this issue on linux via:

Creating a env (environment) variable that clangd looks for called CLANGD_FLAGS and assigning it the path to my c++ 11 path and putting this into my .bashrc file. here is what that looked like:

inside .bashrc

export CLANGD_FLAGS="-I/usr/include/c++/11 --log=Verbose"

NOTE:

  • your path may vary obviously.. Just be sure to precede your path with the -I option.
  • I added the —log=verbose for testing purposes and its not needed.
  • you can also just link the path to a compile_commands.json file if you desire more settings or specifics
    ex:
export CLANGD_FLAGS="--log=verbose --compile-commands-dir=/path/to/compile_commands.json --flag1 --flag2"

@GowrishankarSG05

Did you find solution for this issue. I am facing this issue when I tried to cross compile my project for ARM target

@HighCommander4

Тот же вопрос, но все гораздо запущенней. Скачал и установил Visual Studio Professional 2017, Visual Studio Code, Распространяемый компонент Microsoft Visual C++ для Visual Studio 2017.

Первый урок Hello World^

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
#include "afxstd.h"
#include <iostream>
#include <cstdlib> // для system
using namespace std;
 
int main;
{
cout << "Hallo world!" << endl;
system ("pause");
 
return 0;
 
}

И он не видит ни одной библиотеки (((

Выдает:
The system cannot find the file specified

А в проблемах для каждой из первых трех строк следующее:

message: ‘Include file not found in browse.path.’
at: ‘1,1’

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

Где их взять эти библиотеки? Почему их нет после установки того, что я установил?

  • Печать

Страницы: [1] 2 3  Все   Вниз

Тема: Ошибка компиляции, нет файла iostream.h  (Прочитано 17072 раз)

0 Пользователей и 1 Гость просматривают эту тему.

Оффлайн
F1asher_086

Начал изучать ЯП C++ переписал из учебника простенькую программку вывода

// Программа "Дважды два"
#include <iostream.h>
int main()
{ cout << "2 * 2 =" << 2 * 2 << end1;
return 0;
}

При компиляции возникает ошибка импорта библиотеки iostream:

~$ gcc ~/2+2.cpp

         ~/2+2.cpp:3:22: фатальная ошибка: iostream.h: Нет такого файла или каталога
         компиляция прервана.

Не могу понять в чем дело. Погуглил: в интернетах везде пишут, что ввод/вывод осуществляется библиотекой iostream.
В чем пробема?


Оффлайн
yorik1984

#include <iostream>так надо )))
Плохо учите язык…


Оффлайн
F1asher_086

// Программа "Дважды два"
#include <iostream>
int main()
{ cout << "2 * 2 =" << 2 * 2 << end1;
return 0;
}

В том то и дело , что это тоже не работает:

~$ gcc '/home/some_user/2+2.cpp'
/home/some_user/2+2.cpp: В функции «int main()»:
/home/some_user/2+2.cpp:4:3: ошибка: нет декларации «cout» в этой области видимости
/home/some_user/2+2.cpp:4:3: замечание: suggested alternative:
/usr/include/c++/4.6/iostream:62:18: замечание:   «std::cout»
/home/some_user/2+2.cpp:4:33: ошибка: нет декларации «end1» в этой области видимости


Lifewalker

Господи, где вы находите учебники 15-летней давности? Эти ошибки свойственны древним как ГМ вариантам Си++

// Программа "Дважды два"

// ошибка
// #include <iostream.h>
// нужно так
#include <iostream>

int main()
{
   // тут аж две ошибки. Во-первых пропущен std::
   // во-вторых вместо end1 (end один) нужно писать std::endl (END Line)
   // cout << "2 * 2 =" << 2 * 2 << end1;
   // нужно так
   std::cout << "2 * 2 =" << 2 * 2 << std::endl;
   return 0;
}

Если задолбает каждый раз ставить std::, можно в начале импортнуть пространство имён

#include <iostream>
using namespace std;
// далее по тексту

А лучше всего забейте вы на идиотский Си++ и учите нормальный вменяемый язык типа Модула-2, Оберон-2 или Zonnon. Ну или Ада наконец :)

« Последнее редактирование: 13 Мая 2012, 10:01:50 от Lifewalker »


Оффлайн
F1asher_086

Lifewalker, Спасибо, помогло.

Подскажите кто-нибудь, пожалуйста, более новый учебник по c++, желательно на русском, а то, я так думаю, я неправильно выучу язык.


Оффлайн
yorik1984

вариантов много. Все зависит от начального уровня. Вам надо изучить С++, или программированние с помощью С++. Это разное. В первом случае учебники ориентированны на людей, знакомых с программированием, но в других языках. А во втором случае для «чайников» в этой сфере.


Оффлайн
VlaoMao

А лучше всего забейте вы на идиотский Си++ и учите нормальный вменяемый язык типа Модула-2, Оберон-2 или Zonnon. Ну или Ада наконец :)

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


Lifewalker

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

Второе утверждение вступает в логическую конфронтацию с первым. Сначала вы задаёте уточняющий вопрос, затем затыкаете мне рот, явно давая понять, что не желаете меня слушать. У программиста с логикой должна быть друуужба. Вы программист? ;)

Следует заметить, я дал не только совет, но и решил его проблему; возможно вы проглядели мою подсказку?

Достаточно того, что на подсказанных мною языках пишут программы для спутников, атомных электростанций, управления метрополитеном и так далее. На Си++ их не пишут, потому что Си++ чудовищен, труден, опасен… в общем непригоден для серьёзной работы. Так, баловство, используемое по инерционному недоразумению. Там, где программист на Обероне-2 закончит и сдаст в эксплуатацию модуль, программист на Си++ доберётся до решения проблемы с множественным наследованием, друзьями класса, перегрузкой операторов и разгребёт наконец запутанные вложенные импорты заголовков. В общем, продуктивность ого-го! :)


Оффлайн
Señor_Gaga

А лучше всего забейте вы на идиотский Си++ и учите нормальный вменяемый язык типа Модула-2, Оберон-2 или Zonnon. Ну или Ада наконец :)

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

В настоящее время язык Модула-2 используется для программирования бортового программного обеспечения спутников, запускаемых в рамках проекта ГЛОНАСС
—-
Проекты, использующие Модулу-3

Операционная система SPIN была написана на Модуле-3. Интерфейсы ядра совместимы с DEC Unix.
CVSup — программа для синхронизации репозиториев, также написана на Модуле-3.
—-
Операционные системы, написанные на Аде
MaRTE
RTEMS — ОС с открытым исходным кодом, разработана DARPA МО США
Ravenskar
RTOS-32 — проприетарная ОС


Lifewalker

Понимаете, уважаемый Señor_Gaga, в головах «профессионалов» язык, не позволяющий написать фигню вроде

int main(void)
{
    int i;
    if (i=i++ - ++i) --i;
    return i;
}
не язык вовсе, а так, недоразумение. И ведь этот бред компилируется без ошибок и даже выполняется! Лично я вообще не понимаю, что я тут написал и не представляю что вернёт i, но компилятор понимает и не ругается ни разу. «Профессионалы» видимо тоже увидят в этом сакральный смысл :)


Оффлайн
VlaoMao

Уважаемый Lifewalker, я нисколько не сомневаюсь в Ваших возможностях насрать в теме, но всё же, ответ дали, прекращаем флудить-то, ок?


Оффлайн
yorik1984

А лучше всего забейте вы на идиотский Си++ и учите нормальный вменяемый язык типа Модула-2, Оберон-2 или Zonnon. Ну или Ада наконец :)

А что вы скажете о скриптовых языках типа Руби, Питон, Перл ? Которые являются интерпретируемыми.

Мое мнение такое. Надо учить не конкретный язык и применять во всех местах. А то будет как в

. И еще один….

.
От себя добавлю. Начал учить руби. Пытался очень долго осилить Си и Си++. Так и не понял про ООП. Хотя руби тоже является ООП-ориентированнын языком. Но там как не страно, авторы учебников более наглядно и проще объясняют построение программ с помощью этого метода.

Не могу не согласится с высказыванием Вирта

Никлаус Вирт, создатель языков Паскаль и Модула, один из создателей структурного программирования, утверждает, что ООП — не более чем тривиальная надстройка над структурным программированием, и преувеличение её значимости, выражающееся, в том числе, во включении в языки программирования всё новых модных «объектно-ориентированных» средств, безусловно, вредит качеству разрабатываемого программного обеспечения. Никлаус очень удивлен тем вниманием, которое уделяется ныне ООП.

Взято отсюда http://blogerator.ru/page/oop_why-objects-have-failed

Сколько себя помню, всегда мыслил «процедурно», тоесть структурно.


Оффлайн
Señor_Gaga

Lifewalker

if (i=i++ — ++i) —i; // самый отстойный код, какой я видел

Сам предпочитаю, за редкими исключениями вместо i++ писать i = i + 1;


Lifewalker

А что вы скажете о скриптовых языках типа Руби, Питон, Перл ? Которые являются интерпретируемыми.

А как вы думаете я отношусь к этим … средствам, если единственно расово-верными языками считаю Модулу и Оберон? :)

Руби представляет собой что-то интересное, любопытная игрушка. От Перла ничего кроме испуга испытать невозможно, это же катастрофа. Питон напомнил мне Фортран: я в ужасе от языка, в котором поведение программы можно изменить форматированием текста. В целом не понимаю, как можно писать что-то вменяемое на этих языках. Когда сегодня вижу пол-дистрибуитва на Питоне едва не рыдаю. От впустую потраченного времени программистов (на Обероне то же самое можно было сделать в два раза быстрее и надёжнее) и от изведённых впустую ресурсов (на Обероне то же самое может жрать в 10 раз меньше памяти и в 3 раза меньше тактов процессора).

« Последнее редактирование: 15 Мая 2012, 20:56:08 от Lifewalker »


Оффлайн
RazrFalcon

Ваше мнение можно было бы учитывать, если бы оно было не настолько переполнено фанатизмом.

Еще бы услышать ваше мнение о java/С# и подобных языках, с виртуальной машиной-компилятором.

PS: пишу на Qt(который не c++, а moc  ;)) И не сказал бы что доволен… Но аналогов не вижу, кроме D.


  • Печать

Страницы: [1] 2 3  Все   Вверх

Понравилась статья? Поделить с друзьями:
  • Ошибка insufficient system storage
  • Ошибка internal error 0x8007065b
  • Ошибка io1 initialization failed
  • Ошибка insufficient memory при печати
  • Ошибка internal error 0x06 system error как исправить