Fatal error iostream 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:...

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

Feador

0 / 0 / 0

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

Сообщений: 10

1

25.07.2016, 00:34. Показов 27231. Ответов 13

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


Всем привет !
Я очень давно хотел научиться программировать и вот решил начать . Сначала посоветовали программу Dev C++ , но потом я нашел обучение C++ «Кафедра автоматизации научных исследований Факультет вычислительной математики и кибернетики Московский государственный университет имени М. В. Ломоносова» и там используют Code::blocks + Maple + MinGW . Я скачал и установил эти 3 программы . Запустил Code::Blocks и написал свою 1 программу :

C++
1
2
3
4
5
6
7
#include <iostream>
using namespace std;
int main()
{
   cout << "Hello, World!" << endl;
   return 0;
}

Запустил ее и мне консоль выдала ошибку
build file no target in no project (compiler unknown)
fatal error iostream no such file or directory

Я пошел читать, из-за чего это и понял , что первое может быть из-за отсутствие компиляторанеправильного пути к компилятру. Поменял путь к компелятору и ничего не поменялось . Потом почитал про 2-ое , и мне сказали , что нужно поменять расширение с «c» на «сср» . Попробовал поменять расширение а оно становиться «.ccp.c» .
Вооот… а теперь вопрос : как решить эту проблему ? или может забыть про это обучение , начать самому читать и делать все в Dev C++ и не париться ( там моя 1 программа робит , я проверил ) ????

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



0



Don’t worry, be happy

17781 / 10545 / 2036

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

Сообщений: 26,516

Записей в блоге: 1

25.07.2016, 00:41

3

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

mingw это издевательство над теми кто начинает учить язык.

С чего бы?

Feador, могу предположить,
что Вы проект создаете для C, а не для C++.



0



0 / 0 / 0

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

Сообщений: 10

25.07.2016, 00:45

 [ТС]

4

То есть ты предлагаешь поменять компелятор и все будет нормально ?

Добавлено через 2 минуты
Croessmah , хорошо , а как тогда мне сделать проект в С++ ?



0



Don’t worry, be happy

17781 / 10545 / 2036

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

Сообщений: 26,516

Записей в блоге: 1

25.07.2016, 00:47

5

Feador, когда создаете консольное приложение,
далее предлагается выбрать язык.
Возможно, Вы пропустили это окошко,
машинально нажав «Next».



0



askurandrio

Заблокирован

25.07.2016, 00:53

6

Да потому что когда ты откроешь новый проект в VS у тебя уже будет хелловорлд который скомпилируеться со 100% вероятностью



0



0 / 0 / 0

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

Сообщений: 10

25.07.2016, 00:53

 [ТС]

7

Croessmah , значит мне стоит переустановить приложение или просто в консоле что-нибудь прописать ?



0



Don’t worry, be happy

17781 / 10545 / 2036

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

Сообщений: 26,516

Записей в блоге: 1

25.07.2016, 00:57

8

Лучший ответ Сообщение было отмечено Feador как решение

Решение

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

значит мне стоит переустановить приложение или просто в консоле что-нибудь прописать ?

File -> New -> Project
Выбираете в списке «Console Application», жмете «Go».
Далее или приветствие будет, или выбор языка.
Если первое, то жмете «Next»,
если второе, то выбираете из списка C++, и жмакаете на «Next».
Вводите в новом окне имя проекта, жмете «Next».
В следующем окне оставляете всё как есть, нажимаете «finish».
Это для версии 13.12, думаю, ничего не поменялось.



3



0 / 0 / 0

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

Сообщений: 10

25.07.2016, 00:58

 [ТС]

9

ах да и кстати , как на этом форуме создавать ответ именно одному пользователю (упоминать его)



0



Don’t worry, be happy

17781 / 10545 / 2036

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

Сообщений: 26,516

Записей в блоге: 1

25.07.2016, 01:01

10

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

ах да и кстати , как на этом форуме создавать ответ именно одному пользователю (упоминать его)

Можете выделить нужную часть сообщения и появится «всплывающая» кнопочка «Цитировать».
Клацаете по ней и готово, цитата вставляется в поле ввода.
Или вручную тегами:
[QUOTE="Feador;9398277"]ответ именно одному пользователю[/QUOTE]
Выглядит так:

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

ответ именно одному пользователю

Или можете воспользоваться тегом nick:
[NICK]Croessmah[/NICK]
(выглядит так: Croessmah)
тогда пользователю придет уведомление о том,
что к нему обратились, правда пользователь может
отключить эти уведомления и тогда ему ничего не придет.
Также можете нажать на ник над аватаром пользователя,
это добавит данный тег с ником автоматически в поле ввода.



1



0 / 0 / 0

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

Сообщений: 10

25.07.2016, 01:10

 [ТС]

11

Croessmah кстати сейчас попробовал метод через new -> file и тд. все сработало !!! спасибо огромное ! не ожидал , что так быстро найду решение . Думал буджу ждать ответа овер 999999999 лет ! счастья полные штаны xD



0



Croessmah

25.07.2016, 01:17

Не по теме:

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

счастья полные штаны

Главное, это счастье в код не переносите :jokingly:



0



11 / 11 / 9

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

Сообщений: 85

25.07.2016, 11:49

13

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

«c» на «сср»

Мне одному интересно, что за ccp?



0



Croessmah

25.07.2016, 11:58


    Code::Blocks ошибка компиляции «fatal error iostream no such file or directory»

Не по теме:

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

Мне одному интересно, что за ccp?

Ну очепятался человек, бывает :)



0



Содержание

  1. Ошибка при компиляции
  2. Fatal error: iostream: No such file or directory in compiling C program using GCC
  3. 4 Answers 4
  4. Why can’t g++ find iostream.h?
  5. 3 Answers 3
  6. Visual C++ can’t open include file ‘iostream’
  7. 14 Answers 14
  8. Fatal error iostream no such file or directory что делать

Ошибка при компиляции

Делаю gcc program.c — получаю ошибку «program.c:1:20: fatal error: iostream: No such file or directory #include ^ compilation terminated.»

No such file or directory #include ^ compilation terminated.»

Попробуй perl program.c, должно отработать.

Где мне его взять то?

З.Ы. В Си не силён, особенно под линукс.

неа, кучей ошибок сыпет.

Он издевается. Это C++, поэтому надо использовать g++ и файл переименовать в program.cpp .

а я вот питону хочу поучиться.

нет, это, видимо, кто то с этой прогой поиздевался надо мной. так, ладно, тред этот на сноску.

Это смесь C и C++, также известная как C/C++. Просто в таком виде её надо компилировать уже как C++.

Эх. при компиляции через g++ тонну ошибок ошибок высыпает. буду копаться дальше =)

Читать же надо, как что использовать, а не копировать и пытаться собрать в последний момент. Ошибки линкера, я полагаю:

Не делай так никогда, пожалуйста

Не пиши на суржике — это ни к чему хорошему не приведёт. Толи на том, толи на том — не надо смешивать.

Нужно добавить еще переводов между строками. Иначе квест слишком легкий получается.

А надо «Делаю gcc program.cpp»

Не надо. GCC по расширению файла определит, C это, или C++. В конце концов, можно подсунуть GCC опцию -x lang, где lang — либо c, либо c++, что позволит явно указать, на каком языке пишут в этом файле.

Да что ты говоришь?

Я не знаю, что за скрипт линкера у твоего GCC, что он не подхватывает std::cout и прочие iostreams при компиляции плюсовой программы (пусть даже в ней густо насыпано сишного кода).

Обычный gcc-5.3 из генты, собирается если добавить -lstdc++.

Это понятно, непонятно, отчего её по умолчанию не применяет линкер.

Это понятно, непонятно, отчего её по умолчанию не применяет линкер(при сборке с помощью GNU C Compiler).

Вы откуда такие беретесь?

Это понятно, непонятно, отчего её по умолчанию не применяет линкер(при сборке с помощью GNU C Compiler)

GCC, the GNU Compiler Collection — ты в каком году в криокамеру залёг?

Источник

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:

4 Answers 4

Neither nor are standard C header files. Your code is meant to be C++, where is a valid header. Use a C++ compiler such as clang++ or 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 and using namespace std; , and replace cout with putchar(‘n’); . I advise compiling using C99, C11 or C18 (eg. gcc -std=c99 , clang -std=c18 etc)

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 and using namespace std;

C equivalent for the built-in functions of C++ standard #include can be availed through #include

    Replace #include with #include , delete using namespace std;

With #include taken off, you would need a C standard alternative for cout , 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

When used putchar(‘n’); in the code above in place of cout

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

Источник

Why can’t g++ find iostream.h?

I’m trying to understand how to compile C++ programs from the command line using g++ and (eventually) Clang on Ubuntu.

I found a webpage which explains MakeFiles and I am following their directions. http://mrbook.org/tutorials/make/

I downloaded the four example files into their own directory.

I then went ahead and ran their example of how to manually compile without a MakeFile.

When I ran the command from above, I received the following error from g++:

My only experience with writing c++ is using an IDE such as VS C++ Express or CodeBlocks. Isn’t the compiler supposed to know what iostream.h is and where to find it?

How do I get rid of this error so the program willl compile?

Thanks for any help.

3 Answers 3

Before the C++ language was standardized by the ISO, the header file was named , but when the C++98 standard was released, it was renamed to just (without the .h ). Change the code to use #include instead and it should compile.

You’ll also need to add a using namespace std; statement to each source file (or prefix each reference to an iostream function/object with a std:: specifier), since namespaces did not exist in the pre-standardized C++. C++98 put the standard library functions and objects inside the std namespace.

has never been a standard C++ header, because it did not make it into the C++ standard.

Instead we got , in 1998.

Steer well clear of teaching material using non-standard stuff such as or void main .

However, as a practical solution for your current pre-standard code, you may try to replace

It’s not guaranteed to work, but chances are that it will work.

Another related issue that wasn’t mentioned here, so I will include it for anyone’s future reference, is from the command line the compiler needs the environment path variable updated to find the location of the c++ header files. In windows you can just update the path environment using the ‘advanced system properties’ GUI and add the location of the c++ include files. This will update the PATH environment variable in Windows cmd & Cygwin automatically upon restarting the shell.

To update your PATH from Linux or the Cygwin shell type. PATH=$PATH:/your_path_here Example:PATH=$PATH:/cygdrive/c/cygwin/lib/gcc/i686-pc-mingw32/4.7.3/include/c++ Also a good idea to add just the include directory as well: PATH=$PATH:/cygdrive/c/cygwin/lib/gcc/i686-pc-mingw32/4.7.3/include/ . or check the proper directories for the location of your installation’s include files, I recommend installing mingw for use with Cygwin, which is envoked with g++.

To install additional needed packages in Cygwin re-run the Cygwin install utility & check install from Internet to add packages from web repositories and add mingw-gcc-g++ & mingw-binutils. To compile: g++ hello.cpp -o hello

If using the gcc utility instead compile with the command: gcc hello.cpp -o hello -lstdc++ . to get your executable.

As long as you have either gcc or mingw installed and the path to the c++ include files is in your path environment variable, the commands will work.

Источник

Visual C++ can’t open include file ‘iostream’

I am new to C++. I just started! I tried a code on Visual C++ 2010 Express version, but I got the following code error message.

This is the code:

14 Answers 14

Some things that you should check:

Check the include folder in your version of Visual Studio (in «C:Program FilesMicrosoft Visual Studio xx.xVCinclude», check for the file which you are including, iostream , make sure it’s there).

Check your projects Include Directories in

PropertiesConfiguration PropertiesVC++ DirectoriesInclude Directories (it should look like this: $(VCInstallDir)include;$(VCInstallDir)atlmfcinclude;$(WindowsSdkDir)include;$(FrameworkSDKDir)include; )

Make sure that you selected the correct project for this code (menu FileNewProjectVisual C++Win32 Console Application)

Make sure that you don’t have anywhere in your code files, Visual Studio doesn’t support that (in the same project, check your other code files, .cpp and .h files for and remove it).

Make sure that you don’t have more than one main() function in your project code files (*in the same project, check your other code files, .cpp and .h files for the* main()` function and remove it or replace it with another name).

Some things you could try building with:

  • Exclude using namespace std; from your main() function and put it after the include directive.
  • Use std::cout without using namespace std; .

Источник

Fatal error iostream no such file or directory что делать

My first program won’t run. it says» fatal error: iostream: No such file or directory».
Can someone help?
Thanks in advance.
Rayson

I don’t see any thing wrong with this program you might want

int main( int argc, char* argv[] )

or try and tab over cin.get();

int y;
cin >> y;
return 0;

> it says» fatal error: iostream: No such file or directory».

Use the C++ compiler. For instance, g++ and not gcc.

From the command line, something like:

> I am wondering why the cin.get();is there at all

To make the program wait till the user types in something. Useful, if the program is run in a new terminal window, and without it the window would close instantly.

> when I ran it it my virus protection came up and said it was a threat,
> but i took the cin statement out and it ran fine no problem at all

Your virus protection is talking through its hat.

either of these would work better in my opinion for a beginner programmer

> Well wouldn’t be easier to use a variable? Such as

Formatted input ( >> into a variable) is required if there could be white space left in the buffer after an earlier formatted input.

In general, prefer not using std::system() when you have a reasonable alternative. http://www.cplusplus.com/forum/beginner/93213/

Thank you so much everyone. I am using Code blocks 12.11

Still won’t compile.

> a beginner wouldn’t need to worry about malicious software in their applications would they?
> or is there a virus that attacks new .exe’s as you create them?
> or is it sooooo slow that it would be bad for a beginner to learn?

Programming is a lot easier if one cultivates good habits. And cultivating good habits early is a lot easier than breaking out of bad habits later. Learning x, unlearning x later, and then learning y is a lot harder than learning y in the first place.

Источник

Return to FAQ.


Q: How do I troubleshoot a compiler problem?

A: I would start by turning on full Compiler logging.

This is done by selecting the «Full command line» option Under menu «Settings» -> «Compiler» -> Global compiler settings -> [the compiler you use] -> «Other Setting» tab, «Compiler logging». In 12.11 and newer this is enabled by default.

This option will make Code::Blocks output the exact commands it uses to compile your code.

Things to remember:

  • Look at the «Build Log» NOT the «Build Message» tab
  • Do a re-build instead of build in order to get a full build log.
  • You should review all the commands and their options;
  • If you have compiled your app before, do a re-build (or clean before build) to see all compiling / linking steps;
  • If you don’t know what an option or a command does please read the documentation for the compiler/linker you’re using;
  • Look for missing commands;
  • For every source file (.cpp; .c; .d; etc) in your project, you must have at least one command in the log. This command must produce an object file (file extension .o if using gcc/g++ and .obj if using Visual Studio);
  • Every object file should be linked in the final executable, if not there are undefined symbols errors;
  • Remember the file extension matters: *.c is compiled as C file, *.cpp is compiled as C++ file. Read more
  • If you have no luck, you can try to ask in the forum, but read first «How do I report a compilation problem on the forums»

Q: What do I need to know when using 3rd party libs?

Here are some basics about typical mistakes done when working with third party libs, including wxWidgets. The following is valid for every third party SDK / toolbox / component you want to use and describes what steps your have to do:

  • Download the sources of the component OR a ready-to-use development version. The difference: While the first requires you to compile the component yourself it will definitely work with your compiler. The latter must be compiled in a compatible way: So a compatible compiler, compatible OS, compatible settings. Inspect the components docs about how to get what you want.
  • Place the component sources and compiled parts anywhere you want It is not required to copy such parts to any other folder you might think — in fact, this may even be dangerous in case you overwrite existing files.
  • Create a project where you want to use your component.
  • In the compiler settings (Project->Build Options->Search directories->Compiler), point to the folder, where the include files of your component are. For WX this is special, as usually you include like #include <wx/foo.h>. So do not point to [Component_Folder]includewx, but to [Component_Folder]include instead.
  • Note that the compiler only needs to know the interfaces / classes / structures / methods, it will not throw an error about undefined references or alike. The compiler will only complain in case it cannot find references in terms of include files. If thats the case, adjust your project’s compiler settings. Keep in mind that you do need to fulfil the requirements of your component itself, too. Thus, wxChart for example will need for wxWidgets, too. So — you may need to do the same process for wxWidgets, too before you can use wxChart — unless you have done that already.
  • In the linker settings (Project->Build Options->Search directories->Linker), point to the folder where you have your compiled library. A library usually ends with *.a or *.lib. Note that there are generally two types of libs: Static libs (after linking you are done) and Dynamic libs (where you link against an import lib but require another dynamic lib at runtime).
  • In the linker settings (Project->Build Options->Linker settings) add the library/libraries you need to link against in the right order to the list of libs to link against. Order matters — again, dependencies must be taken into account. Inspect the developers guide of the component to know the dependencies. On Windows, this may include the MSDN, too which tells you what libraries you need to link against for certain symbols you or the library may make use of.
  • The linker will never complain about includes it cannot find. Because the linker just links object files or library files together. But the linker may complain about unresolved symbols which you need to provide. So if that happens, either your setup is missing a lib, or the order is wrong.

Again, this is valid for all third party stuff you want to use. Its heavily platform and compiler dependent. The IDE should be less of concern for you. Every IDE can be setup in a way it will compile and link your stuff unless you provide everything needed as explained above.

If you don’t understand parts written here it is strongly recommended you start with a book about general programming in C/C++ that covers library handling in more detail.

For the example wxChart in the end is not easy for starters. Usually you need to compile wxWidgets before, then wxChart and usually not all dependencies are explained in the docs and it behaves differently on different OS’es / compilers. Also, wcChart can be compiled in many flavours — so you need to make sure the flavour matches a) your needs and b) the way you compiled wxWidgets.

Q: My simple C++ program throws up lots of errors — what is going on?

If you have a C++ program like this:

 #include <iostream>
 int main() {
   std::cout << "hello worldn";
 }

and when you compile it you get errors like this:

 fatal error: iostream: No such file or directory

then you have probably given your source file a .c extension. If you do that, the GCC compiler (and others) will probably attempt to compile the file as a C program, not as C++. You should always give your C++ source files the extension .cpp to make sure the compiler handles them correctly.

Q: I imported a MSVCToolkit project/workspace, but Code::Blocks insists on trying to use GCC. What’s wrong?

A: A little documentation problem ^^;. The «default compiler» is usually GCC, so when you imported it with «the default compiler», you told it to use GCC. To fix this situation, go to «Project», «Build Options» and select VC++ Toolkit as your compiler.

Another possibility is to put the Microsoft compiler as the default one. To do this, choose Settings — Compiler, choose the Microsoft compiler in the Selected Compiler section (top of dialog box) and press the Set as default button.

From now onwards, for all new projects the Microsoft compiler will be taken by default.

Q: When compiling a wxWidgets project, I get several «variable ‘vtable for xxxx’ can’t be auto-imported». What’s wrong?

A: You need to add WXUSINGDLL in «Project->Build options->Compiler #defines» and rebuild your project (or create a new project and use the «Using wxWidgets DLL» project option which adds «-DWXUSINGDLL» to Project->Build options->Other options).
Other errors with the same resolution are:
‘unresolved external symbol «char const * const wxEmptyString» (?wxEmptyString@@3PBDB)’ or similar.
If you were using 1.0-finalbeta and were trying to build a statically linked wxWidgets project, the cause of the problem was some faulty templates. But that’s fixed now.

Q: I can’t compile a multithreaded app with VC Toolkit! Where are the libraries?

A: Sorry, no fix for your problem…

Your problem doesn’t come from CodeBlocks. It exists, because the free VC toolkit (VCTK) doesn’t provide all the libraries and tools which come with Visual C++ (VC) which isn’t free, unfortunately.

Try buying a full-fledged VC++, or even better, download MinGW

The libraries that can be obtained free of charge are:

Paths:

(VCT3) Visual C++ Toolkit 2003 - C:Program FilesMicrosoft Visual C++ Toolkit 2003lib
(PSDK) Platform SDK - C:Program FilesMicrosoft Platform SDKLib
(NSDK) .NET 1.1 SDK - C:Program FilesMicrosoft Visual Studio .NET 2003Vc7lib

C runtime libs:

LIBC.LIB 	Single-threaded, static link                                          (VCT3, NSDK)
LIBCMT.LIB 	Multithreaded, static link                                            (VCT3, NSDK)
MSVCRT.LIB 	Multithreaded, dynamic link (import library for MSVCR71.DLL)          (NSDK)
LIBCD.LIB 	Single-threaded, static link (debug)                                  (VCT3, NSDK)
LIBCMTD.LIB 	Multithreaded, static link (debug)                                    (NSDK)
MSVCRTD.LIB 	Multithreaded, dynamic link (import library for MSVCR71D.DLL) (debug) (NSDK)

C++ libs:

LIBCP.LIB 	Single-threaded, static link                                          (VCT3, PSDK)
LIBCPMT.LIB 	Multithreaded, static link                                            (VCT3)
MSVCPRT.LIB 	Multithreaded, dynamic link (import library for MSVCP71.dll)          (none)
LIBCPD.LIB 	Single-threaded, static link (debug)                                  (VCT3)
LIBCPMTD.LIB 	Multithreaded, static link (debug)                                    (none)
MSVCPRTD.LIB 	Multithreaded, dynamic link (import library for MSVCP71D.DLL) (debug) (none)

Try setting the library linker directories to:

C:Program FilesMicrosoft Visual C++ Toolkit 2003lib
C:Program FilesMicrosoft Platform SDKLib
C:Program FilesMicrosoft Visual Studio .NET 2003Vc7lib

in that order.

The ones listed as (none) above are actually present in the IA64 and AMD64 subdirectories of the PSDK lib directory. Not sure if these would work on 32-bit windows, however, they may if they are
meant to work in 32-bit compatibility mode on the 64-bit processors. Worth a try. Otherwise, you
can link statically to the C++ library instead of using MSVCP71.dll. If you really want to link against MSVCP71.dll you can try to create MSVCP71.LIB from the dll using lib.exe and sed. Search google for «exports.sed» for detailed steps.

See also: tclsh script to extract import .lib from (any?) DLL (MinGW)

See also: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vclib/html/_crt_c_run.2d.time_libraries.asp

See also: http://sapdb.2scale.net/moin.cgi/MS_20C_2b_2b_20Toolkit

Q: I get this error when compiling: Symbol «isascii» was not found in «codeblocks.dll»

A: Make sure you didn’t mix up the MSVC headers or libs with the MinGW ones.

Q: My build fails with multiple undefined reference errors?

Example:

undefined reference to `WSACleanup@8
undefined reference to `WSACleanup@0

A: Most of the time it is because the required library is not linked with your project. Go to Project->Build options…->Linker settings (tab) and add the required library or libraries.

If the error includes a line number, it is likely that this is a problem with your code. Track down down your function declarations and implementations. Ensure they all match up, are spelled correctly, and have the correct scope resolution.

VERY often you can get help by just googling for the name of the undefined reference, for this example its «WSACleanup». Usually one of the first links is the SDK documentation, like this from MSDN for WSACleanup. You’ll find there a lot useful information, including what libraries you need to link against, as for the exsample:
Requirements

  • Minimum supported client: Windows 2000 Professional
  • Minimum supported server: Windows 2000 Server
  • Header: Winsock2.h
  • Library: Ws2_32.lib
  • DLL: Ws2_32.dll

The header file Winsock2.h you need to include in your sources. Most likely you have done that already because otherwise you would have gotten a compiler error unable to find the function declaration. The library you need to link against, you can remove any prefix like «lib» and the file extension like «.lib», «.a» or «.so» — so just type «Ws2_32» in the linker options. Also make sure you have added the path to that library in the linker include path’s options, otherwise the linker will complain that it cannot find that library you want to link against. You also know, that you should distribute Ws2_32.dll for the runtime version of you app, luckily this one usually ships with Windows anyways, so no need to do something here.

Q: My build fails in the compile/link/run step with a Permission denied error?

A: There are several possible causes for this:

  1. The output directory does not have read/write access.
    • Either change control settings on the output directory, or move the project to different location.
  2. A previous instance of the executable failed to terminate properly.
    • Open your system’s equivalent of Process/Task Manager, search the list for the name of the executable Code::Blocks is trying to output, and terminate it.
    • Logging off or rebooting will achieve the same effect.
  3. The executable is open.
    • If the executable is open in a hex-editor or actively being run, close it.
  4. Security software is interfering.
    • The target file is locked while an antivirus programming is scanning it; either wait a few seconds for the antivirus scan to finish, set an exception in the antivirus settings, or (temporarily) disable the antivirus program.
    • Firewalls with very strict settings sometimes block execution; try reducing the firewall’s settings or adding an exception.
    • Switching security software may have left traces behind that are interfering; hunt down the remnants of the old antivirus/firewall software and remove them.
  5. The file/library cannot be found.
    • Double check all of the compiler and linker search directories (including any variables they may be using) are properly setup.
  6. Code::Blocks was improperly installed.
    • Mixing binaries from a stable release and a nightly build (or even two different nightly builds) is highly likely to cause a slew of problems; reinstall Code::Blocks in an empty directory.
  7. Multiple installed compilers are interfering with each other.
    • If they are not required to keep, completely remove all but the most used compiler.
    • If several compilers are required, ensure that none of them are in the system path (this is so that Code::Blocks will be able to manage all paths).
    • Also, do not place any compilers in their default installation path (for example C:MinGW), as some compilers are hard-coded to look for headers in a default path before searching their own respective directories.
  8. On windows 7, the service «Application Experience» is not running as explained on stackoverflow.

See also: [/index.php/topic,15047.0.html Permission denied forums discussion]

Q: My build fails to link due to multiple definition of xyz errors?

A: GCC 4.6.1 mingw target (Windows) is known to occasionally (and erroneously) report this if link-time optimization (-flto) is used.

First, of course, check that no token has been defined multiple times. If the source code is clean, and yet the errors persist, adding linker switch (Project->Build options…->Linker settings (tab))

-Wl,--allow-multiple-definition

will enable the code to link.

See also: Bug 12762

Q: How can I change the language of the compiler (gcc) output to english?

A: Codeblocks 12.11 or higher: Settings->Environment->Environment Variables. Add «LC_ALL» with value «C». ->Set Now -> Ok

Since a few releases gcc is localized. This can make difficult to find (google  ;) ) solutions for specific problems. With this setting the output is again in english.

!! this can break displaying of non-aschii characters so you can also use LC_ALL = en_US.utf8 (/index.php/topic,17579.msg120613.html#msg120613)


Return to FAQ.

  • Forum
  • Beginners
  • fatal error: iostream: No such file or d

fatal error: iostream: No such file or directory.

I am trying to find my first compiler to begin coding and compiling files on. I have just downloaded Code::Blocks (after searching for hours and even downloading and trying multiple different compilers (all to which have led to failures and had to be uninstalled)) and coded the following:

1
2
3
4
5
6
7
8
9
 #include <iostream>
using namespace std;

int main()
{
    cout << "Hello world!";

    return 0;
}

Using what I thought was the compiler that is stored in the Code::Blocks files, I tried executing the program with GNU GCC Compiler.

When I tried to build the program, nothing happened. When I tried running the program, an error window popped up telling me that the program hadn’t been built.
Further investigation of the Build Messages lead me to an error statement suggesting the following:

«fatal error: iostream: No such file or directory.»

I am trying to get this compiler to work but I don’t know what to do. I’ve tried other compiler options but Build Messages tell me that I don’t seem to have any other compilers.

Help.

NOTE: The first line of code (containing ‘#include <iostream>’) was marked since I received the error message in the Build Messages.

ANOTHER NOTE: I don’t know if I’m being as specific as I can. Is there something that I am supposed to check (like the Build Messages) that would help me give you useful information? I.E.- Is there anything you want to know specifically? I’m new and I don’t know what to look for when things mess up like they did on my computer.

Hi,
You need to use g++, instead of gcc. Then it should work fine.

Thanks for the tip. Although I ended up getting Orwell Dev-C++ instead.

g++ didn’t come up on the list of compilers I could use.

Make sure that the name of the file identifies it as a C++ source file.

For instance: not main.c, but main.cpp or main.cc

Topic archived. No new replies allowed.

Почему, когда я хочу скомпилировать следующую многопоточную программу сортировки слиянием, я получаю эту ошибку:

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.

Моя программа:

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

5

Решение

ни <iostream> ни <iostream.h> являются стандартными заголовочными файлами C. Ваш код предназначен для C ++, где <iostream> является действительным заголовком. использование g++.cpp расширение файла) для кода C ++.

Кроме того, эта программа использует в основном конструкции, которые в любом случае доступны в Си. Достаточно просто преобразовать всю программу для компиляции с использованием компилятора Си. Просто удалить #include <iostream> а также using namespace std;и заменить cout << endl; с putchar('n');… советую компилировать с использованием C99 (например. gcc -std=c99)

24

Другие решения

Похоже, вы опубликовали новый вопрос после того, как поняли, что имеете дело с более простой проблемой, связанной с size_t, Я рад, что ты это сделал.

В любом случае, у вас есть .c исходный файл, и большая часть кода выглядит в соответствии со стандартами C, за исключением того, что #include <iostream> а также using namespace std;

C эквивалент для встроенных функций стандарта C ++ #include<iostream> можно получить через #include<stdio.h>

  1. замещать #include <iostream> с #include <stdio.h>, удалять using namespace std;
  2. С #include <iostream> снял, вам понадобится стандартная альтернатива С для cout << endl;что может быть сделано printf("n"); или же putchar('n');
    Из двух вариантов, printf("n"); работает быстрее, как я заметил.

    Когда используется printf("n"); в приведенном выше коде вместо cout<<endl;

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

    Когда используется putchar('n'); в приведенном выше коде вместо cout<<endl;

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

Скомпилировано с Cygwin gcc (GCC) 4.8.3 версия. результаты усреднены по 10 выборкам. (Заняло у меня 15 минут)

4

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Fatal error insufficient shared memory reg ru
  • Fatal error insufficient power configured
  • Fatal error in vertex shader compilation
  • Fatal error in twain device driver
  • Fatal error in object unshallow

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

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