[c++] Fatal error: iostream: No such file or directory in compiling C program using GCC

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;
}

This question is related to c++ c gcc g++

The answer is


Neither <iostream> nor <iostream.h> are standard C header files. Your code is meant to be C++, where <iostream> is a valid header. Use g++ (and a .cpp file extension) for C++ code.

Alternatively, this program uses mostly constructs that are available in C anyway. It's easy enough to convert the entire program to compile using a C compiler. Simply remove #include <iostream> and using namespace std;, and replace cout << endl; with putchar('\n');... I advise compiling using C99 (eg. gcc -std=c99)


Seems like you posted a new question after you realized that you were dealing with a simpler problem related to size_t. I am glad that you did.

Anyways, You have a .c source file, and most of the code looks as per C standards, except that #include <iostream> and using namespace std;

C equivalent for the built-in functions of C++ standard #include<iostream> can be availed through #include<stdio.h>

  1. Replace #include <iostream> with #include <stdio.h>, delete using namespace std;
  2. With #include <iostream> taken off, you would need a C standard alternative for cout << endl;, which can be done by printf("\n"); or putchar('\n');
    Out of the two options, printf("\n"); works the faster as I observed.

    When used printf("\n"); in the code above in place of cout<<endl;

    $ time ./thread.exe
    1 2 3 4 5 6 7 8 9 10
    
    real    0m0.031s
    user    0m0.030s
    sys     0m0.030s
    

    When used putchar('\n'); in the code above in place of cout<<endl;

    $ time ./thread.exe
    1 2 3 4 5 6 7 8 9 10
    
    real    0m0.047s
    user    0m0.030s
    sys     0m0.030s
    

Compiled with Cygwin gcc (GCC) 4.8.3 version. results averaged over 10 samples. (Took me 15 mins)


Questions with c++ tag:

Method Call Chaining; returning a pointer vs a reference? How can I tell if an algorithm is efficient? Difference between opening a file in binary vs text How can compare-and-swap be used for a wait-free mutual exclusion for any shared data structure? Install Qt on Ubuntu #include errors detected in vscode Cannot open include file: 'stdio.h' - Visual Studio Community 2017 - C++ Error How to fix the error "Windows SDK version 8.1" was not found? Visual Studio 2017 errors on standard headers How do I check if a Key is pressed on C++ How to enable C++17 compiling in Visual Studio? Remove from the beginning of std::vector Why does C++ code for testing the Collatz conjecture run faster than hand-written assembly? What is (x & 1) and (x >>= 1)? What are the new features in C++17? Visual Studio Code includePath Compiling an application for use in highly radioactive environments "No rule to make target 'install'"... But Makefile exists How to build and use Google TensorFlow C++ api Error LNK2019 unresolved external symbol _main referenced in function "int __cdecl invoke_main(void)" (?invoke_main@@YAHXZ) Converting std::__cxx11::string to std::string lvalue required as left operand of assignment error when using C++ How to overcome "'aclocal-1.15' is missing on your system" warning? MSVCP140.dll missing How to get image width and height in OpenCV? CMake error at CMakeLists.txt:30 (project): No CMAKE_C_COMPILER could be found Reading json files in C++ What exactly is std::atomic? Compile c++14-code with g++ Visual Studio 2015 doesn't have cl.exe Visual Studio 2013 error MS8020 Build tools v140 cannot be found CMake does not find Visual C++ compiler Casting int to bool in C/C++ C++ How do I convert a std::chrono::time_point to long and back How can I get the size of an std::vector as an int? Significance of ios_base::sync_with_stdio(false); cin.tie(NULL); Fatal error: iostream: No such file or directory in compiling C program using GCC unresolved external symbol __imp__fprintf and __imp____iob_func, SDL2 How to end C++ code How to change text color and console color in code::blocks? Error: stray '\240' in program invalid use of non-static member function Convert float to string with precision & number of decimal digits specified? enum to string in modern C++11 / C++14 / C++17 and future C++20 Passing capturing lambda as function pointer How do I add a library path in cmake? error: expected primary-expression before ')' token (C) undefined reference to 'std::cout' java.lang.UnsatisfiedLinkError: dalvik.system.PathClassLoader fatal error: mpi.h: No such file or directory #include <mpi.h>

Questions with c tag:

conflicting types for 'outchar' Can't compile C program on a Mac after upgrade to Mojave Program to find largest and second largest number in array Prime numbers between 1 to 100 in C Programming Language In c, in bool, true == 1 and false == 0? How I can print to stderr in C? Visual Studio Code includePath "error: assignment to expression with array type error" when I assign a struct field (C) Compiling an application for use in highly radioactive environments How can you print multiple variables inside a string using printf? How to resolve the "EVP_DecryptFInal_ex: bad decrypt" during file decryption How does one set up the Visual Studio Code compiler/debugger to GCC? How to add a char/int to an char array in C? Fork() function in C Warning comparison between pointer and integer Unsigned values in C How to run C program on Mac OS X using Terminal? How to printf a 64-bit integer as hex? Casting int to bool in C/C++ Significance of ios_base::sync_with_stdio(false); cin.tie(NULL); "Multiple definition", "first defined here" errors error C4996: 'scanf': This function or variable may be unsafe in c programming Fatal error: iostream: No such file or directory in compiling C program using GCC What is the symbol for whitespace in C? How to change text color and console color in code::blocks? How to build x86 and/or x64 on Windows from command line with CMAKE? error: expected primary-expression before ')' token (C) C compile : collect2: error: ld returned 1 exit status How to use execvp() What does "collect2: error: ld returned 1 exit status" mean? socket connect() vs bind() fatal error: mpi.h: No such file or directory #include <mpi.h> How to scanf only integer? Abort trap 6 error in C Can someone explain how to append an element to an array in C programming? Returning string from C function Difference between using Makefile and CMake to compile the code How to convert const char* to char* in C? C convert floating point to int "break;" out of "if" statement? How to compile and run C in sublime text 3? How do I use setsockopt(SO_REUSEADDR)? Reading string by char till end of line C/C++ How to set all elements of an array to zero or any same value? The differences between initialize, define, declare a variable how to stop a loop arduino 'readline/readline.h' file not found size of uint8, uint16 and uint32? warning: control reaches end of non-void function [-Wreturn-type] Char Comparison in C

Questions with gcc tag:

Can't compile C program on a Mac after upgrade to Mojave Compiling an application for use in highly radioactive environments Make Error 127 when running trying to compile code How to Install gcc 5.3 with yum on CentOS 7.2? How does one set up the Visual Studio Code compiler/debugger to GCC? How do I set up CLion to compile and run? CMake error at CMakeLists.txt:30 (project): No CMAKE_C_COMPILER could be found How to printf a 64-bit integer as hex? Differences between arm64 and aarch64 Fatal error: iostream: No such file or directory in compiling C program using GCC How to change text color and console color in code::blocks? undefined reference to 'std::cout' "Agreeing to the Xcode/iOS license requires admin privileges, please re-run as root via sudo." when using GCC setup script exited with error: command 'x86_64-linux-gnu-gcc' failed with exit status 1 How does #include <bits/stdc++.h> work in C++? How to compile and run C in sublime text 3? version `CXXABI_1.3.8' not found (required by ...) Can't find file executable in your configured search path for gnc gcc compiler Debugging the error "gcc: error: x86_64-linux-gnu-gcc: No such file or directory" gcc: undefined reference to fatal error: Python.h: No such file or directory (.text+0x20): undefined reference to `main' and undefined reference to function libpthread.so.0: error adding symbols: DSO missing from command line g++ ld: symbol(s) not found for architecture x86_64 GCC fatal error: stdio.h: No such file or directory Compilation fails with "relocation R_X86_64_32 against `.rodata.str1.8' can not be used when making a shared object" Why does the C preprocessor interpret the word "linux" as the constant "1"? installing vmware tools: location of GCC binary? Why do I get "a label can only be part of a statement and a declaration is not a statement" if I have a variable that is initialized after a label? Why does configure say no C compiler found when GCC is installed? Do I need to compile the header files in a C program? How to specify new GCC path for CMake mingw-w64 threads: posix vs win32 String in function parameter How do I link object files in C? Fails with "Undefined symbols for architecture x86_64" How do you disable the unused variable warnings coming out of gcc in 3rd party code I do not wish to edit? Build .so file from .c file using gcc command line gdb: how to print the current line or find the current line number? What is the "Illegal Instruction: 4" error and why does "-mmacosx-version-min=10.x" fix it? gcc-arm-linux-gnueabi command not found How to recompile with -fPIC Cannot find libcrypto in Ubuntu Printf long long int in C with GCC? Unable to specify the compiler with CMake printf not printing on console gcc/g++: "No such file or directory" How do I print uint32_t and uint16_t variables value? ld cannot find -l<library> typeof operator in C Gcc error: gcc: error trying to exec 'cc1': execvp: No such file or directory

Questions with g++ tag:

How do I set up CLion to compile and run? Compile c++14-code with g++ Fatal error: iostream: No such file or directory in compiling C program using GCC How does #include <bits/stdc++.h> work in C++? DSO missing from command line C++ unordered_map using a custom class type as the key How do I enable C++11 in gcc? usr/bin/ld: cannot find -l<nameOfTheLibrary> cc1plus: error: unrecognized command line option "-std=c++11" with g++ to_string is not a member of std, says g++ (mingw) How do I install g++ for Fedora? gcc/g++: "No such file or directory" How to make g++ search for header files in a specific directory? openCV program compile error "libopencv_core.so.2.4: cannot open shared object file: No such file or directory" in ubuntu 12.04 Eclipse C++ : "Program "g++" not found in PATH" Is optimisation level -O3 dangerous in g++? C++ compile time error: expected identifier before numeric constant Compiling C++11 with g++ C++ Error 'nullptr was not declared in this scope' in Eclipse IDE std::enable_if to conditionally compile a member function Using 'sudo apt-get install build-essentials' How do I include a path to libraries in g++ Link error "undefined reference to `__gxx_personality_v0'" and g++ error: use of deleted function How to create a static library with g++? extra qualification error in C++ How to see which flags -march=native will activate? error: expected class-name before ‘{’ token Error: free(): invalid next size (fast): Missing include "bits/c++config.h" when cross compiling 64 bit program on 32 bit in Ubuntu LD_LIBRARY_PATH vs LIBRARY_PATH C++ undefined reference to defined function How to forward declare a template class in namespace std? Compiling a C++ program with gcc Undefined reference to vtable What is the purpose of using -pedantic in GCC/G++ compiler? How to specify preference of library path? How do I capture all of my compiler's output to a file? GCC dump preprocessor defines How do I install g++ on MacOS X? gcc warning" 'will be initialized after' Disable all gcc warnings GCC C++ Linker errors: Undefined reference to 'vtable for XXX', Undefined reference to 'ClassName::ClassName()' Update GCC on OSX How to make a variadic macro (variable number of arguments) Compiling with g++ using multiple cores g++ undefined reference to typeinfo Undefined reference to static class member What is the difference between g++ and gcc?