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;
}
Facing compilation errors can be frustrating, especially when the error messages are not very helpful. In this guide, we will discuss how to resolve the `fatal error: iostream: No such file or directory` error that occurs while compiling C++ programs.
## Table of Contents
1. [Understanding the Error](#understanding-the-error)
2. [Step-by-Step Solution](#step-by-step-solution)
3. [FAQs](#faqs)
4. [Related Links](#related-links)
## Understanding the Error
This error occurs when the compiler is unable to locate the iostream header file, which is a crucial part of the C++ Standard Library. It provides functionality for input and output operations, such as reading from the keyboard and displaying text on the screen. The most common reasons for this error are:
- Incorrectly including the header file
- Using an outdated or misconfigured compiler
## Step-by-Step Solution
### Step 1: Verify the Header File Inclusion
Make sure you have included the iostream header file correctly in your source code. The correct syntax is:
```cpp
#include <iostream>
If you have used a different syntax, like #include "iostream"
, change it to the correct one and recompile your code.
Step 2: Check the Compiler Installation
If the error still persists, check if your compiler is installed correctly. You can do this by running the following command in your terminal or command prompt:
g++ --version
If you get an error or the version number is lower than 5.1, consider updating your compiler.
Step 3: Verify the Compiler’s Include Path
The compiler needs to know where to find the header files. You can check the default include path by running the following command:
g++ -E -x c++ - -v < /dev/null
Look for the «include» directory in the output. If it does not contain the path to the iostream header file, you may need to reinstall your compiler or update the include path manually.
Step 4: Update the Include Path Manually (Optional)
If you have determined that the include path is the problem, you can update it manually by adding the -I
option followed by the path to the iostream header file when compiling your code. For example:
g++ -I/path/to/your/include/directory your_source_file.cpp -o your_output_file
FAQs
The iostream header file is a part of the C++ Standard Library that provides functionality for input and output operations, such as reading from the keyboard and displaying text on the screen.
2. Why am I getting the «fatal error: iostream: No such file or directory» error?
This error occurs when the compiler is unable to locate the iostream header file, which can be due to an incorrect inclusion, an outdated or misconfigured compiler, or an incorrect include path.
3. How can I check if my compiler is installed correctly?
You can check if your compiler is installed correctly by running the following command in your terminal or command prompt:
g++ --version
4. How can I update my compiler?
You can update your compiler by following the official installation guide.
5. Is it possible to manually update the include path?
Yes, you can update the include path manually by adding the -I
option followed by the path to the iostream header file when compiling your code.
- GCC Installation Guide
- C++ Standard Library Reference
- Common C++ Compilation Errors
«`
You should change iostream.h
to iostream
. I was also getting the same error as you are getting, but when I changed iostream.h
to just iostream
, it worked properly. Maybe it would work for you as well.
In other words, change the line that says:
#include <iostream.h>
Make it say this instead:
#include <iostream>
The C++ standard library header files, as defined in the standard, do not have .h
extensions.
As mentioned Riccardo Murri’s answer, you will also need to call cout
by its fully qualified name std::cout
, or have one of these two lines (preferably below your #include
directives but above your other code):
using namespace std;
using std::cout;
The second way is considered preferable, especially for serious programming projects, since it only affects std::cout
, rather than bringing in all the names in the std
namespace (some of which might potentially interfere with names used in your program).
Aliaxandr 9 / 9 / 8 Регистрация: 03.07.2015 Сообщений: 219 |
||||
1 |
||||
01.09.2015, 03:36. Показов 20177. Ответов 12 Метки нет (Все метки)
Привет всем. Беда такая. Все время пока что учил только С, теперь думаю взяться за С++. Помню, когда установил линукс, требовалось докачать еще какие то пакеты данных, потому что на Си не компилировалась простая программа Hello world. Порылся и нашел на одном английскоязычном форуме комманду, которую надо было по просту выполнить в консоли, после чего все заработало. Так вот вопрос как это сделать для С++.
выдает следующую ошибку:
0 |
kalonord 28 / 28 / 5 Регистрация: 27.01.2014 Сообщений: 784 |
||||
01.09.2015, 03:58 |
2 |
|||
Я могу ошибаться, но разве не
? Добавлено через 13 секунд Не по теме: или нет разницы?
1 |
163 / 104 / 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 |
|||
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 день вот такой вот пример, который у меня не работает:
Может быть просто нужна другая среда разработки?(я работаю в консоли на линуксе)
0 |
2761 / 1915 / 569 Регистрация: 05.06.2014 Сообщений: 5,571 |
|
14.09.2015, 14:12 |
7 |
Может быть просто нужна другая среда разработки? Нужна машина времени. В прошлом веке такой код действительно компилировался, но в этом уже устарел.
1 |
9 / 9 / 8 Регистрация: 03.07.2015 Сообщений: 219 |
|
14.09.2015, 15:04 [ТС] |
8 |
Renji, может посоветуешь книгу для начинающих, чтобы вот без таких вот траблов???потомучто это не первая книга, где я встречаю такой пример кода для программы, которая по просту печатает Hello world!
0 |
940 / 868 / 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 |
может посоветуешь книгу для начинающих «Как программировать на С++», Дейтелы. Чего так долго на «Hello, World» сидишь? Не по теме: А что за метода освоить С++ за 21 день? Действующая?
1 |
117 / 121 / 42 Регистрация: 25.08.2012 Сообщений: 1,294 |
|
06.10.2015, 01:16 |
12 |
Renji, а что было с пространствами имен тогда? По-моему, неймспейсы были фишкой плюсов еще тогда. Или ради совместимости можно было не указывать?
0 |
2761 / 1915 / 569 Регистрация: 05.06.2014 Сообщений: 5,571 |
|
07.10.2015, 08:12 |
13 |
Renji, а что было с пространствами имен тогда? Тогда еще не придумали убрать всю стандартную библиотеку в std::.
1 |
0
1
Есть программа:
#include <iostream>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdio.h>
#include <dirent.h>
#include <string.h>
#include <stdlib.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <sys/syscall.h>
#include <pthread.h>
#include <cstdio>
using namespace std;
void* procInfo(void*);
mode_t readUmasl();
int cntOpenFiles();
void printArgv();
void printCodDataStackEnvSegment();
char** argvG;
int argcG;
extern char** environ;
int main(int argc, char** argv)
{
argvG = (char**)malloc(argc*sizeof(char*));
memcpy(argvG, argv, argc*sizeof(char*));
argcG = argc;
procInfo(NULL);
if(!fork())
{
//printf("-------------------CHILD_PROC-------------------n");
cout << "-------------CHILD PROCESS-------------" << "n";
procInfo(NULL);
}
wait();
pthread_t thread_id;
//printf("------------------IN_THREAD-----------------n");
cout << "-------------IN THREAD-------------"<< "n";
pthread_create(&thread_id, NULL, procInfo, NULL);
pthread_join(thread_id, NULL);
pause();
return 0;
pause();
}
void* procInfo(void* data )
{
cout << "PID: " << getpid() << "n";
cout << "PPID: " << getppid() << "n";
cout << "UID: " << getuid() << "n";
cout << "GID: " << getgid() << "n";
cout << "SID: " << getsid(getpid()) << "n";
cout << "PGID: " << getpgid(getpid()) << "n";
cout << "UMASK: "<< readUmasl() << "n";
cout <<"Control terminal:";
if(isatty(0))
cout << ttyname(0);
else
cout <<"closed";
cout <<"n";
char buff[256];
getcwd(buff, 256);
cout << "Current directory: " <<buff<< "n";
cout << "count open files: " << cntOpenFiles() << "n";
cout << "Priority: " << getpriority(PRIO_PROCESS, getpid());
printf("n-------------------Priority-------------------n");
setpriority(PRIO_PROCESS, getpid(),5);
cout << "Priority: " << getpriority(PRIO_PROCESS, getpid());
printArgv();
printCodDataStackEnvSegment();
return NULL;
}
mode_t readUmasl()
{
mode_t mask = umask(0);
umask(mask);
return mask;
}
int cntOpenFiles()
{
char buff[256];
sprintf(buff,"/proc/%i/fd",getpid());
DIR *dir = opendir(buff);
int i=0;
dirent* entry;
while((entry = readdir(dir))!=NULL)
{
++i;
}
closedir(dir);
i -= 3;
return i;
}
void printArgv()
{
for(int i=0; i <argcG; i++)
{
cout << argvG[i];
}
cout << "n";
}
void printCodDataStackEnvSegment()
{
// Cod segment 1
char buffer[256];
sprintf(buffer, "/proc/%i/maps", getpid());
FILE *map = fopen(buffer, "r");
fgets(buffer,256,map);
char *pCodSegStart = strtok(buffer, "-");
char *pCodSegEnd = strtok(NULL, " ");
cout << "Code segment: " << pCodSegStart <<" " << pCodSegEnd << "n";
// Data segment 3
char buffer1[256];
fgets(buffer1,256,map);
fgets(buffer1,256,map);
char *pDataStart = strtok(buffer1, "-");
char *pDataEnd = strtok(NULL, " ");
cout << "Data segment: " << pDataStart <<" " << pDataEnd<< "n";
fclose(map);
// Stack segment 3 с конца
if (syscall(SYS_gettid) == getpid())
{
cout << "in main thread n";
char buff[256];
sprintf(buff, "/proc/%i/maps", getpid());
map = fopen(buff, "r");
int i = 0;
while(fgets(buff,256,map) != NULL){
++i;
}
rewind(map);
int j = 0;
for (; j != i - 2; ++j ){
fgets(buff, 256, map);
}
fclose(map);
char *pStackStart = strtok(buff, "-");
char *pStackFinish = strtok(NULL, " ");
cout << "Stack segment: " << pStackStart <<" " << pStackFinish<< "n";
}
else
{
void *addr;
size_t size;
pthread_t self;
pthread_attr_t attr;
self = pthread_self();
pthread_getattr_np(self, &attr);
pthread_attr_getstackaddr(&attr, &addr);
pthread_attr_getstacksize(&attr, &size);
cout << "in non main thread now n";
printf("stack addr = %0lxn", addr);
printf("stack addr = %0lxn", addr-size);
}
// Env segment
cout << "Enviroment segment: "<< environ[0] << " ";
int i = 0;
while(environ[i + 1] != NULL) {
++i;
}
cout << environ[i] + strlen(environ[i]) + 1 << "n";
}
Делаю gcc program.c — получаю ошибку «program.c:1:20: fatal error: iostream: No such file or directory
#include <iostream>
^
compilation terminated.»
В чем причина?