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).
Jesusus 0 / 0 / 0 Регистрация: 21.09.2017 Сообщений: 6 |
||||
1 |
||||
25.09.2017, 18:39. Показов 8672. Ответов 4 Метки нет (Все метки)
Здравствуйте! Суть проблемы в шапке. Сказали найти код программы на курсовую, нашёл, не компилируется. В чем проблема? Пробовал вместо iostream.h — iostream, не помогло. Дописывать строку using namespace std; так же не помогло.
0 |
Заклинатель змей 611 / 508 / 213 Регистрация: 30.04.2016 Сообщений: 2,412 |
|
25.09.2017, 18:45 |
2 |
Сообщение было отмечено Jesusus как решение РешениеJesusus, попробуйте <> вместо «»
1 |
0 / 0 / 0 Регистрация: 21.09.2017 Сообщений: 6 |
|
25.09.2017, 18:50 [ТС] |
3 |
Jesusus, попробуйте <> вместо «» [Error] C:/Program Files (x86)/Dev-Cpp/MinGW64/lib/gcc/x86_64-w64-mingw32/4.9.2/include/c++/stdlib.h»: Invalid argument Добавлено через 58 секунд
0 |
Заклинатель змей 611 / 508 / 213 Регистрация: 30.04.2016 Сообщений: 2,412 |
|
25.09.2017, 18:52 |
4 |
Jesusus, не знаком с Dev, но проблема видится в путях к заголовкам, проверьте в настройках или свойствах проекта
1 |
0 / 0 / 0 Регистрация: 21.09.2017 Сообщений: 6 |
|
25.09.2017, 19:04 [ТС] |
5 |
Jesusus, не знаком с Dev, но проблема видится в путях к заголовкам, проверьте в настройках или свойствах проекта Уже решил проблему. Оказывается необходимо было убрать формат .h , дописать using namespace std; и вместо void main () вписать int main(void) Спасибо за помощь!
0 |
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.»
В чем причина?