I downloaded Code::Blocks from here: http://www.codeblocks.org/downloads/26
I’m learning c programming. When I run the following program, I get error:
iostream: No such file or directory
error: syntax error before "namespace"
warning: type defaults to `int' in declaration of `std'
warning: data definition has no type or storage class
In function `main':
error: `cout' undeclared (first use in this function)
error: (Each undeclared identifier is reported only once
error: for each function it appears in.)
error: `cin' undeclared (first use in this function)
I’m running the following program:
#include <iostream>
using namespace std;
int main()
{
int x;
x = 0;
do {
// "Hello, world!" is printed at least one time
// even though the condition is false
cout<<"Hello, world!n";
} while ( x != 0 );
cin.get();
}
I tried Dev-C++, I get the same error.
How to fix this?
asked Apr 22, 2012 at 18:23
2
Is this in a file like «program.c» or «program.cpp»? If it’s a .c file, then your compiler may be interpreting it as C, and not C++. This could easily cause such an error. It’s possible to «force» the compiler to treat either such extension as the other, but by default, .c files are for C, and .cpp files are compiled as C++.
It’s either this, or somehow your default «include» directories for the standard library are not set up right, but I don’t know how you’d fix that, as that’d be compiler/environment dependent.
answered Apr 22, 2012 at 19:04
Kevin AndersonKevin Anderson
6,6264 gold badges31 silver badges54 bronze badges
I also had that problem when trying to run my first program in Code::Blocks. My file was saved with ‘.c’ extension as ‘test.c’ and when I saved it as ‘test.cpp’, it worked fine.
It is also worth mentioning that I had to restart Code::Blocks before new ‘test.cpp’ file was compiled successfully.
answered May 25, 2013 at 6:09
OlexiyOlexiy
5371 gold badge7 silver badges14 bronze badges
While saving your source code before compiling just save the name with extension «.cpp». You wont get the error..
answered Nov 9, 2015 at 9:03
I got the same problem.
Change #include < iostream.h >
to #incude < iostream >
Consequently, in your program, change every keyword related to iostream, such as cin cout and endl to std::cout, std::cin and std::endl
That’ll do the trick
answered Apr 21, 2014 at 10:39
Aseem AhirAseem Ahir
5931 gold badge5 silver badges7 bronze badges
Use <iostream>
instead of <iostream.h>
and add std::
before cout
, cin
etc
Use std::cout << "Welcome";
instead of cout << "Welcome";
Save the file with .cpp
extension
Machavity♦
30.5k27 gold badges90 silver badges100 bronze badges
answered Apr 17, 2015 at 20:08
you have missing iostream.h file in you mingw directory folder placed inside codeblocks/devc++. what you have to do is just download the file from link given below and replace with your previous mingw folder in codeblocks/devc++.
http://www.4shared.com/rar/owp-D0Km/mingw.html
answered Jun 3, 2014 at 14:47
I found the problem was cause by having a previous version of cgg and cpp in a Perl installation. The Perl structure did not have the correct library files. When I added C:MinGWbin
and C:MinGWMSYS1.0bin
to the path, I added them at the end so it picked up the Perl install first. I moved the path variable entries to the beginning and reopened my cmd window and it now works because it finds the MinGW version first.
Type path to see your path environment varialble. Mine now looks like:
C:MinGW>path
PATH=C:MinGWbin;C:MinGWMSYS1.0bin;C:Perlsitebin;C:Perlbin;C:WINDOWSsystem32;C:WINDOWS;C:WINDOWSSystem32Wbem;C:WINDOWSSystem32WindowsPowerShellv1.0;C:Program FilesWIDCOMMBluetoothSoftware;
udondan
55.6k19 gold badges192 silver badges172 bronze badges
answered Mar 12, 2015 at 9:38
Apparently you want to create a c++ file. But you allowed your computer to auto provide the file extension C/C++. When it does that it automatically provides a file extension of «.c». Which is not corect. You want «.cpp».
Solution: Rename your file with a «.cpp» extension, or else explicitly state your extension when saving new files by putting «.cpp» (without quotes of course) after your intended file name; i.e. specify your file extension.
answered Jul 6, 2018 at 21:58
I tried in Dev-C++ . Instead of iostream.h use iostream also write the using namespace std;
#include<iostream>
using namespace std;
int main()
{
cout<<"Hello Worldn";
return 0;
}
answered Apr 9, 2020 at 5:28
you written your program in C++ code use c code then your program run correctly
in first line use it
#include <Io stream.h>
main ()
{
in ending line use it
system (pause");
answered Nov 23, 2013 at 2:18
You are trying to make a C game right? If you are your code is C++ not C. So if you are trying to make a C game than you should change your code. This might help.
answered Apr 13, 2016 at 22:37
zanezane
111 gold badge2 silver badges7 bronze badges
Just put «Using namespace std;» before main() to define the scope of identifiers you are using. This will handle your problem easily.
answered Jun 30, 2017 at 4:55
1
Try including iostream.h
instead of iostream
.
Anthony
12k9 gold badges69 silver badges104 bronze badges
answered Apr 22, 2012 at 18:26
1
Feador 0 / 0 / 0 Регистрация: 25.07.2016 Сообщений: 10 |
||||
1 |
||||
25.07.2016, 00:34. Показов 27155. Ответов 13 Метки нет (Все метки)
Всем привет !
Запустил ее и мне консоль выдала ошибку Я пошел читать, из-за чего это и понял , что первое может быть из-за отсутствие компиляторанеправильного пути к компилятру. Поменял путь к компелятору и ничего не поменялось . Потом почитал про 2-ое , и мне сказали , что нужно поменять расширение с «c» на «сср» . Попробовал поменять расширение а оно становиться «.ccp.c» .
__________________
0 |
Don’t worry, be happy 17781 / 10545 / 2036 Регистрация: 27.09.2012 Сообщений: 26,516 Записей в блоге: 1 |
|
25.07.2016, 00:41 |
3 |
mingw это издевательство над теми кто начинает учить язык. С чего бы? Feador, могу предположить,
0 |
0 / 0 / 0 Регистрация: 25.07.2016 Сообщений: 10 |
|
25.07.2016, 00:45 [ТС] |
4 |
То есть ты предлагаешь поменять компелятор и все будет нормально ? Добавлено через 2 минуты
0 |
Don’t worry, be happy 17781 / 10545 / 2036 Регистрация: 27.09.2012 Сообщений: 26,516 Записей в блоге: 1 |
|
25.07.2016, 00:47 |
5 |
Feador, когда создаете консольное приложение,
0 |
Заблокирован |
|
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 |
Решение
значит мне стоит переустановить приложение или просто в консоле что-нибудь прописать ? File -> New -> Project
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 |
ах да и кстати , как на этом форуме создавать ответ именно одному пользователю (упоминать его) Можете выделить нужную часть сообщения и появится «всплывающая» кнопочка «Цитировать».
ответ именно одному пользователю Или можете воспользоваться тегом nick:
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
|
Не по теме:
счастья полные штаны Главное, это счастье в код не переносите :jokingly:
0 |
11 / 11 / 9 Регистрация: 01.07.2015 Сообщений: 85 |
|
25.07.2016, 11:49 |
13 |
«c» на «сср» Мне одному интересно, что за ccp?
0 |
Croessmah |
25.07.2016, 11:58
|
Не по теме:
Мне одному интересно, что за ccp? Ну очепятался человек, бывает
0 |
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:
- The output directory does not have read/write access.
- Either change control settings on the output directory, or move the project to different location.
- 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.
- The executable is open.
- If the executable is open in a hex-editor or actively being run, close it.
- 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.
- 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.
- 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.
- 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.
- 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.
Содержание
- FAQ-Compiling (errors)
- Namespaces
- Page actions
- Contents
- Q: How do I troubleshoot a compiler problem?
- Q: What do I need to know when using 3rd party libs?
- Q: My simple C++ program throws up lots of errors — what is going on?
- Q: I imported a MSVCToolkit project/workspace, but Code::Blocks insists on trying to use GCC. What’s wrong?
- Q: When compiling a wxWidgets project, I get several «variable ‘vtable for xxxx’ can’t be auto-imported». What’s wrong?
- Q: I can’t compile a multithreaded app with VC Toolkit! Where are the libraries?
- Q: I get this error when compiling: Symbol «isascii» was not found in «codeblocks.dll»
- Q: My build fails with multiple undefined reference errors?
- Q: My build fails in the compile/link/run step with a Permission denied error?
- Q: My build fails to link due to multiple definition of xyz errors?
- Q: How can I change the language of the compiler (gcc) output to english?
- Fatal error: iostream: No such file or directory in compiling C program using GCC
- 4 Answers 4
FAQ-Compiling (errors)
Namespaces
Page actions
Contents
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 . 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:
and when you compile it you get errors like this:
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:
Try setting the library linker directories to:
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.
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?
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:
- The output directory does not have read/write access.
- Either change control settings on the output directory, or move the project to different location.
- 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.
- The executable is open.
- If the executable is open in a hex-editor or actively being run, close it.
- 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.
- 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.
- 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.
- 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.
- 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))
will enable the code to link.
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.
Источник
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)
Источник
Dear all,
I only just started with C++ i downloaded the tutorial from this site and started writing. iam using winAVR-20100110.
As you can see i allready removed the #include <iostream> because this directive came up with an error. the file is named main.c and the makefile has been named main.
below the code as writen right now.
|
|
when i click «make all» the following happens:
> «make.exe» all
——— begin ———
avr-gcc (WinAVR 20100110) 4.3.3
Copyright (C) 2008 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
Compiling C: main.c
avr-gcc -c -mmcu=atmega32 -I. -gdwarf-2 -DF_CPU=8000000UL -Os -funsigned-char -funsigned-bitfields -fpack-struct -fshort-enums -Wall -Wstrict-prototypes -Wa,-adhlns=./main.lst -std=gnu99 -MMD -MP -MF .dep/main.o.d main.c -o main.o
main.c:4: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘namespace’
main.c:9: warning: function declaration isn’t a prototype
main.c: In function ‘main’:
main.c:11: error: ‘cout’ undeclared (first use in this function)
main.c:11: error: (Each undeclared identifier is reported only once
main.c:11: error: for each function it appears in.)
make.exe: *** [main.o] Error 1
> Process Exit Code: 2
> Time Taken: 00:06
Due to my very low amount of experience iam not surten what could be the problem, and i hope you can help me out.
Kind Regards,
Maulus
|
|
Edit: Should of read properly =/
Last edited on
i allready removed the #include <iostream> because this directive came up with an error.
But what was the error? Since that line is needed in this case (because you use cout), that’s the problem which needs to be addressed.
Could that be a big clue? It looks like you are using a C compiler…
I should want to stab Olysold:
http://www.urbandictionary.com/define.php?term=should%20of
Your compiler acts weird imho.
main.c:4: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘namespace’
Wait, why?
using namespace x; is a core language feature as far as I know.
Get a better compiler like microsoft’s, clang, or GCC (MinGW on windows I think).
Also rename main.c to .cpp, some compilers (I heard) may apply a C compiler to .c files.
main.c:11: error: 'cout' undeclared (first use in this function)
Should really be accessible through <iostream>, how can it come up with an error?
Maybe changing the file name from
main.c
to
main.cpp
will cause it to be detected and compiled as c++. Or there may be some compiler option to switch between c and c++ ?
Last edited on
When main.c is renamed as main.cpp:
> «make.exe» all
make.exe: *** No rule to make target `all’. Stop.
> Process Exit Code: 2
> Time Taken: 00:00
When #include <iostream>:
> «make.exe» all
make.exe: *** No rule to make target `all’. Stop.
> Process Exit Code: 2
> Time Taken: 00:01
there is a drop down menu where i can pick from a whole list of…things
a few are:
plain text
c#
Css
D
Diff
Ada
C/C++ (this one is selected)
because the program comes back with make.exe i reckonned there might be something in the make file thats wrong?
Earlier i forgot to mention the .cpp file changed the icon it now contains the letters C++. as for the .c file the icon gives just C.
Last edited on
«make.exe» is a part of the compiler, no?
Try downloading Code::Blocks and MinGW as a bundle, you can get it at http://www.codeblocks.org/downloads
Then choose «Download the binary release»
Then choose «codeblocks-12.11mingw-setup.exe»
It’s free and it should compile «Hello World» without problems
Last edited on
Grey Wolf wrote: |
---|
«Could that be a big clue? It looks like you are using a C compiler…« |
S/he is. S/he is using AVR-GCC: a 3rd-party C library for use with GCC based on Atmel AVR micro-controllers.
@Maulus: You need to get rid of the compiler you’re using now and replace it with a better compiler. May I recommend either GNU’s GCC compiler, preferably one that supports C++, or Microsoft’s compiler. Code::Blocks, and IDE, is shipped with GNU’s C++-supporting compiler by default. Microsoft’s Visual Express is shipped with their own compiler which also supports C++.
Code::Blocks: http://www.codeblocks.org/
Visual Express: http://www.microsoft.com/visualstudio/eng/products/visual-studio-express-for-windows-desktop
Wazzak
You can also use Orwell Dev-Cpp. http://sourceforge.net/projects/orwelldevcpp/files/Portable%20Releases/Dev-Cpp%205.4.1%20MinGW%204.7.2%20Portable.7z/download
i want to thank you all for the fast and helpfull replys after downloading and installing code::blocks and Orwell Dev-Cpp and implementing the «hello world» program they both come with the same problems:
error: unknown type name ‘using’
error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘std’
error: ‘cout’ undeclared (first use in this function)
main.c:3:20: fatal error: iostream: No such file or directory
i think i’am doing something wrong, i hope you guys are able to help me out!
i allso read somewhere that the iostream header has become obselete with the new compilers, this could be the reason why iam unable to find it anywhere.
Thanks,
Maulus
Last edited on
What’s your compiler?
in C::B:
Settings -> Compiler -> Selected Compiler
GNU GCC compiler
Honestly, just go download code::blocks with minigw, it will solve all this and you can concentrate on learning the details of compilers later when you understand the language better.
thats the one i installed.
Maulus wrote: |
---|
error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘std’ |
This is the same error you got before, isn’t it? I think Code::Blocks has mixed up the compilers.
Try uninstalling your compiler (the one you mentioned earlier — WinAVR), then re-installing Code::Blocks with MinGW. (or have you already done that?)
Afterwards, go to Settings -> Compiler and click the «Reset defaults» button on the top right. It should sort itself out.
Last edited on
i just uninstalled all compiler’s including Code::blocks, made sure every single visual file has been removed.
reinstalled code::blocks 12.11 minGW
compiler = GNU GCC compiler.
(did aswell reset to default)
and yet again exactly the same error’s, its starting to piss me off now to be honest, it can’t be that hard right?!
Have you tried following Code::Blocks’ Wiki page[1]?
[1]http://wiki.codeblocks.org/index.php?title=Creating_a_new_project
Wazzak
And does the code you are compiling look exactly like this?
|
|
I have been able to reproduce the problem by creating a file called main.c with code Chervil posted.
You really need to use a C++ compiler and not a C compiler. Are you compiling manually? Just use the little gear (compile) button in Code Blocks.
Recommended Answers
How are you creating your project?
Jump to Post
I remember now, I had the same problem. Did you type .cpp at the end of your file name lol?
Jump to Post
All 8 Replies
11 Years Ago
How are you creating your project?
Nikhar
19
Junior Poster in Training
11 Years Ago
@firstperson
How am I creating my project? I am sorry but what’s that question supposed to mean?
11 Years Ago
@firstperson
How am I creating my project? I am sorry but what’s that question supposed to mean?
You possibly might have created a project with wrong dependencies. When I say create a project, I mean with code blocks. Maybe you have created the wrong type of project. Else you need to manually link the needed headers.
Nikhar
19
Junior Poster in Training
11 Years Ago
@firstperson
I don’t think I’m running any project. I mean, I opened codeblocks and began working straight away.
@sergent
Its Windows XP SP2
11 Years Ago
I remember now, I had the same problem. Did you type .cpp at the end of your file name lol?
Nikhar
19
Junior Poster in Training
11 Years Ago
@sergent
lol..guess what..it worked. Apparently, codeblocks was saving it as a C file by default so thats why there were all these errors. Adding cpp at the end does the trick. Thanks
pc75
0
Newbie Poster
10 Years Ago
This forum proved helpful. Thank you.
Reply to this topic
Be a part of the DaniWeb community
We’re a friendly, industry-focused community of developers, IT pros, digital marketers,
and technology enthusiasts meeting, networking, learning, and sharing knowledge.
Почему, когда я хочу скомпилировать следующую многопоточную программу сортировки слиянием, я получаю эту ошибку:
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>
- замещать
#include <iostream>
с#include <stdio.h>
, удалятьusing namespace std;
-
С
#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