Меню

Ошибка iostream h no such file or directory

Why when I wan to compile the following multi thread merge sorting C program, I receive this error:

ap@sharifvm:~/forTHE04a$ gcc -g -Wall -o mer mer.c -lpthread
mer.c:4:20: fatal error: iostream: No such file or directory
 #include <iostream>
                    ^
compilation terminated.
ap@sharifvm:~/forTHE04a$ gcc -g -Wall -o mer mer.c -lpthread
mer.c:4:22: fatal error: iostream.h: No such file or directory
 #include <iostream.h>
                      ^
compilation terminated.

My program:

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <iostream>
using namespace std;

#define N 2  /* # of thread */

int a[] = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1};  /* target array */

/* structure for array index
 * used to keep low/high end of sub arrays
 */
typedef struct Arr {
    int low;
    int high;
} ArrayIndex;

void merge(int low, int high)
{
        int mid = (low+high)/2;
        int left = low;
        int right = mid+1;

        int b[high-low+1];
        int i, cur = 0;

        while(left <= mid && right <= high) {
                if (a[left] > a[right])
                        b[cur++] = a[right++];
                else
                        b[cur++] = a[right++];
        }

        while(left <= mid) b[cur++] = a[left++];
        while(right <= high) b[cur++] = a[left++];
        for (i = 0; i < (high-low+1) ; i++) a[low+i] = b[i];
}

void * mergesort(void *a)
{
        ArrayIndex *pa = (ArrayIndex *)a;
        int mid = (pa->low + pa->high)/2;

        ArrayIndex aIndex[N];
        pthread_t thread[N];

        aIndex[0].low = pa->low;
        aIndex[0].high = mid;

        aIndex[1].low = mid+1;
        aIndex[1].high = pa->high;

        if (pa->low >= pa->high) return 0;

        int i;
        for(i = 0; i < N; i++) pthread_create(&thread[i], NULL, mergesort, &aIndex[i]);
        for(i = 0; i < N; i++) pthread_join(thread[i], NULL);

        merge(pa->low, pa->high);

        //pthread_exit(NULL);
        return 0;
}

int main()
{
        ArrayIndex ai;
        ai.low = 0;
        ai.high = sizeof(a)/sizeof(a[0])-1;
        pthread_t thread;

        pthread_create(&thread, NULL, mergesort, &ai);
        pthread_join(thread, NULL);

        int i;
        for (i = 0; i < 10; i++) printf ("%d ", a[i]);
        cout << endl;

        return 0;
}

Aliaxandr

9 / 9 / 8

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

Сообщений: 219

1

01.09.2015, 03:36. Показов 19277. Ответов 12

Метки нет (Все метки)


Привет всем. Беда такая. Все время пока что учил только С, теперь думаю взяться за С++. Помню, когда установил линукс, требовалось докачать еще какие то пакеты данных, потому что на Си не компилировалась простая программа Hello world. Порылся и нашел на одном английскоязычном форуме комманду, которую надо было по просту выполнить в консоли, после чего все заработало. Так вот вопрос как это сделать для С++.
Данный код:

C++ (Qt)
1
2
3
4
5
6
7
8
#include<iostream.h>
 
int main(){
 
count<<"Hello World!n";
 
return 0;
}

выдает следующую ошибку:
sasha@sasha-eM355 ~/programming $ gcc -Wall -o hello hello.cpp
hello.cpp:1:21: fatal error: iostream.h: No such file or directory
#include<iostream.h>
^
compilation terminated.

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



0



kalonord

28 / 28 / 5

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

Сообщений: 784

01.09.2015, 03:58

2

Я могу ошибаться, но разве не

C++
1
#include <iostream>

?

Добавлено через 13 секунд

Не по теме:

или нет разницы?



1



160 / 101 / 14

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

Сообщений: 488

01.09.2015, 03:59

3

вместо <iostream.h> напишите <iostream>, а вместо gcc вызывайте g++



1



kalonord

28 / 28 / 5

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

Сообщений: 784

01.09.2015, 04:04

4

C++
1
std::cout



1



9 / 9 / 8

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

Сообщений: 219

01.09.2015, 04:31

 [ТС]

5

спасибо, теперь все заработало



0



Aliaxandr

9 / 9 / 8

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

Сообщений: 219

14.09.2015, 14:04

 [ТС]

6

kalonord, iRomul, тогда вопрос, почему в книге Освой С++ за 21 день вот такой вот пример, который у меня не работает:

C++
1
2
3
4
5
6
7
//Листинг 1.1. Файл HELLO.cpp — программа приветствия.
   #include <iostream.h>
   int main()
   {
       cout << "Hello World!n"
       return 0;
   }

Может быть просто нужна другая среда разработки?(я работаю в консоли на линуксе)



0



2758 / 1912 / 569

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

Сообщений: 5,561

14.09.2015, 14:12

7

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

Может быть просто нужна другая среда разработки?

Нужна машина времени. В прошлом веке такой код действительно компилировался, но в этом уже устарел.



1



9 / 9 / 8

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

Сообщений: 219

14.09.2015, 15:04

 [ТС]

8

Renji, может посоветуешь книгу для начинающих, чтобы вот без таких вот траблов???потомучто это не первая книга, где я встречаю такой пример кода для программы, которая по просту печатает Hello world!



0



939 / 867 / 355

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

Сообщений: 2,706

14.09.2015, 15:36

9

Можешь здесь посмотреть: Литература C++
, или набери в поиске по форуму: «Литература для начинающего».



1



28 / 28 / 5

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

Сообщений: 784

06.10.2015, 01:08

11

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

может посоветуешь книгу для начинающих

«Как программировать на С++», Дейтелы.

Чего так долго на «Hello, World» сидишь?

Не по теме:

А что за метода освоить С++ за 21 день? Действующая?



1



117 / 121 / 42

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

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

06.10.2015, 01:16

12

Renji, а что было с пространствами имен тогда? По-моему, неймспейсы были фишкой плюсов еще тогда. Или ради совместимости можно было не указывать?



0



2758 / 1912 / 569

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

Сообщений: 5,561

07.10.2015, 08:12

13

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

Renji, а что было с пространствами имен тогда?

Тогда еще не придумали убрать всю стандартную библиотеку в std::.



1



  • Forum
  • Beginners
  • fatal error: iostream.h: No such file or

fatal error: iostream.h: No such file or directory

Hello all,

Finally I have started writting tiny programs in C++.
And here is my first question: I am trying to use #include <iostream.h> in a simple c++ program.
I am using cygwin and I am able to compile and execute this program and others well when I use #include <iostream>.
But when I use #include <iostream.h> I get error as:

$ g++ Test1.cpp -o Test1
Test1.cpp:1:22: fatal error: iostream.h: No such file or directory
#include <iostream.h>
^
compilation terminated.

Is this expected or am I missing something? Should .h I read that both iostream and iostream.h should work.
Here is code I have put in

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream.h>

using namespace std;

int main()
{
	float number1, number2, sum, average;
	cout << "Enter two numbers: ";	//prompt
	cin >> number1;	//Reads numbers
	cin >> number2; //from keyboard
	
	sum = number1 + number2;
	average = sum/2;
	
	cout << "Sum = " << sum << "n";
	cout << "Average = " << average << "n";
	
	return 0;
}

<iostream>

g++ does not come with iostream.h, only some very old versions of Borland compilers do. You should always use <iostream> these days.

Ok, got it.
Thanks for such speedy response Mats, modoran & Catfish666.

Last edited on

Topic archived. No new replies allowed.

Introduction

In this intermittent series, I’ll be looking at the most common error messages your C++ compiler (and linker) can produce, explaining exactly what they mean, and showing how they can be fixed (or, better still avoided). The article will specifically talk about the errors produced by the GCC command line compiler, but I’ll occasionally provide some coverage of Microsoft C++ as well. The articles are aimed at beginner to intermediate C++ programmers, and will mostly not be OS-specific.

Error Messages 101

Compiler error messages from the GCC g++ compiler generally look like something this:

main.cpp: In function 'int main()':
main.cpp:4:12: error: 'bar' was not declared in this scope

which was produced by this code:

int main() {
    int foo = bar;
}

The first line of the error says which function the following error(s) is in. The error message itself comes in four main parts; the file the error occurs in, the line number and character offset at which the compiler thinks the error occurs, the fact that it is an error, and not a warning, and the text of the message.

As well as error, the compiler can also produce warnings. These are usually about constructs that, while not being actually illegal in C++, are considered dubious, or constructs that the compiler has extensions to cover. In almost all cases, you don’t want to use such constructs, and you should treat warnings as errors; in other words, your code should always compile with zero warnings. You should also increase the level of warnings from the compiler’s default, which is usually too low. With g++, you should use at least the -Wall and -Wextra compiler options to do this:

g++ -Wall -Wextra myfile.cpp

No such file or directory

The error I’m looking at today most commonly occurs when you are including a header file using the preprocessor #include directive. For example, suppose you have the following code in a file called myfile.cpp:

#include "myheader.h"

and you get the following error message:

myfile.cpp:1:22: fatal error: myheader.h: No such file or directory
compilation terminated.

What could be causing it? Well, the basic cause is that the compiler cannot find a file called myheader.h in the directories it searches when processing the #include directive. This could be so for a number of reasons.

The simplest reason is that you want the compiler to look for myheader.h in the same directory as the myfile.cpp source file, but it can’t find it. this may be because you simply haven’t created the header file yet, but the more common reason is that you either misspelled the header file name in the #include directive, or that you made a mistake in naming  the header file when you created it with your editor. Look very closely at the names in both the C++ source and in your source code directory listing. You may be tempted to think «I know that file is there!», but if the compiler says it isn’t there, then it isn’t, no matter how sure you are that it is.

This problem is somewhat greater on Unix-like system, such as Linux, as there file names are character case sensitive, so Myheader.h, MyHeader.h, myheader.h and so on would all  name different files, and if you get the case wrong, the compiler will not look for something «similar». For this reason, a very good rule of thumb is:

Never use mixed case when naming C++ source and header files. Use only alphanumeric characters and the underscore when naming C+++ files. Never include spaces or other special characters in file names.

Apart from avoiding file not found errors, this will also make life much easier if you are porting your code to other operating systems which may or may not respect character case.

The wrong directory?

Another situation where you may get this error message is if you have split your header files up from your C++ source files into separate directories. This is generally good practice, but can cause problems. Suppose your C++ project is rooted at C:/myprojects/aproject, and that in the aproject directory you have two sub-directorys called src (for the .cpp files) and inc (for the header files), and you put myfile.cpp  in the src directory, and myheader.h in the inc directory, so that you have this setup:

myprojects
  aproject
    inc
      myheader.h
    src
      myfile.cpp

Now if you compile the source myfile.cpp from the src directory, you will get the «No such file or directory» error message. The C++ compiler knows nothing about the directory structures of your project, and won’t look in the inc directory for the header. You need to tell it to look there somehow.

One thing some people try when faced with this problem is to re-write myfile.cpp so it looks like this:

#include "c:/myprojects/aproject/inc/myheader.h"

or the slightly more sophisticated:

#include "../inc/myheader.h"

Both of these are a bad idea, as they tie your C++ code to the project’s directory structure and/or location, both of which you will probably want to change at some point in the future. If the directory structure does change, you will have to edit all your #include directories.The better way to deal with this problem is to tell the compiler directly where to look for header files. You can do that with the compiler’s -I option, which tells the compiler to look in the specified directory, as well as the ones it normally searches:

g++ -Ic:/myprojects/aproject/inc myfile.cpp

Now the original #include directive:

#include "myheader.h"

will work, and if your directory structure changes you need only modify the compiler command line. Of course, writing such command lines is error prone, and you should put such stuff in a makefile, the use of which is unfortunately outside the scope of this article.

Problems with libraries

Somewhat similar issues to those described above can occur when you want to use a third-party library.  Suppose you want to use the excellent random number generating facilities of the Boost library. If you are copying example code, you may well end up with something like this in your C++ source file:

#include "boost/random.hpp"

This will in all probability lead to yet another «No such file or directory» message, as once again the compiler does not know where «boost/random.hpp» is supposed to be. In fact, it is one of the subdirectories of the Boost installation, and on my system I can get the #include directive to work using this command line:

g++ -Ic:/prog/boost1461 myfile.cpp

where /prog/boost1461 is the root directory for my specific Boost library installation.

Can’t find C++ Standard Library files?

One last problem that beginners run into is the inability of the compiler to find header files that are part of the C++ Standard Library. One particular favourite is this one:

#include <iostream.h>

where you are learning C++ from a very, very old book. Modern C++ implementations have not contained a file called iostream.h for a very long time indeed, and your compiler is never going to find it. You need to use the correct, standard names for such headers (and to get a better book!):

#include <iostream>

If this still fails, then there is almost certainly something very wrong with your GCC installation. The GCC compiler looks for Standard Library files in a subdirectory of its installation, and locates that directory relative to the directory containing the compiler executable, so if the Standard Library headers are available, the compiler should always find them.

Conclusion

This article looked at the «No such file or directory»  message of the GCC C++ compiler.  If you get this message you should:

  • Remember that the compiler is always right in situations like this.
  • Look very closely at the file name to make sure it is correct.
  • Avoid naming file using mixed-case or special characters.
  • Use the -I compiler option to tell the compiler where to look for files.
  • Make sure that GCC is correctly installed on your system.
  • Remove From My Forums
  • Question

  •  Hi All:

     The story so far:

     I am having a we bit of trouble running

     the most difficult of all C++ programs the

     imfamous first C++ program Hello World!

     code:

     // Simple Hello World Console Application
    #include <iostream>
    using namespace std;
    int main()
    {
         cout << «nHello World!n» << endl;
         return 0;
    }

    And we get:

    —— Build started: Project: Hello, Configuration: Debug Win32 ——

    Compiling…

    hello.cpp

    f:program filesmicrosoft sdkbinhellohello.cpp(2) : fatal error C1083: Cannot open include file: ‘iostream.h’: No such file or directory

    Build log was saved at «file://f:Program FilesMicrosoft SDKBinHelloDebugBuildLog.htm»

    Hello — 1 error(s), 0 warning(s)

    ========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

     What is really wrong this is the second

     time I have installed C++ and still is not

     running at all.

Answers

  • <iostream>
    is normally stored in the C:Program FilesMicrosoft Visual Studio
    8VCinclude folder.  First check if it is still there.  Then
    choose Tools + Options, Projects and Solutions, VC++ Directories,
    choose «Include files» in the «Show Directories for»  combobox and
    double-check that $(VCInstallDir)include is on top of the list.

  • Check all of your code to make sure you’ve not included iostream.h anywhere.  C++ Express edition has no idea what iostream.h is, as it’s not standard C++, this is the first edition to (finally) remove it altogether.

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Ошибка iommu windows 10
  • Ошибка io netty channel abstractchannel annotatedconnectexception майнкрафт hamachi