0.8 — A few common C++ problems

In this section, we’ll address some of the common issues that new programmers seem to run across with fairly high probability. This is not meant to be a comprehensive list of compilation or execution problems, but rather a pragmatic list of solutions to very basic issues. If you have any suggestions for other issues that might be added to this list, post them in the comments section below.

General run-time issues

Q: When executing a program, the console window blinks and then closes immediately.

First, add or ensure the following lines are near the top of your program (Visual Studio users, make sure these lines appear after #include “pch.h” or #include “stdafx.h”, if those exist):

Second, add the following code at the end of your main() function (right before the return statement):

This will cause your program to wait for the user to press a key before continuing, which will give you time to examine your program’s output before your operating system closes the console window.

Other solutions, such as the commonly suggested system(“pause”) solution may only work on certain operating systems and should be avoided.

Older versions of Visual Studio may not pause when the program is run in Start With Debugging (F5) mode. Try running in Start Without Debugging (Ctrl-F5) mode.

Q: I ran my program and get a window but no output.

Your virus scanner or anti-malware may be blocking execution. Try disabling it temporarily and see if that’s the issue.

Q: My program compiles but it isn't working correctly. What do I do?

Debug it! There are tips on how to diagnose and debug your programs later in chapter 3.

General compile-time issues

Q: When I compile my program, I get an error about unresolved external symbol _main or [email protected]

This means your compiler can’t find your main() function. All programs must include a main() function.

There are a few things to check:
a) Does your code include a function named main?
b) Is main spelled correctly?
c) When you compile your program, do you see the file that contains function main() get compiled? If not, either move the main() function to one that is, or add the file to your project (see lesson 2.7 -- Programs with multiple code files for more information about how to do this).
d) Did you create a console project? Try creating a new console project.

Q: I'm trying to use C++11/14/17/XX functionality and it doesn't work

If your compiler is old, it may not support these more recent additions to the language. In that case, upgrade your compiler.

For modern IDEs/compilers, your compiler may be defaulting to an older language standard. We cover how to change your language standard in lesson 0.12 -- Configuring your compiler: Choosing a language standard.

Q: When trying to use cin, cout, or endl, the compiler says cin, cout, or endl is an 'undeclared identifier'

First, make sure you have included the following line near the top of your file:

Second, make sure each use of cin, cout, and endl are prefixed by “std::”. For example:

If this doesn’t fix your issue, then it may be that your compiler is out of date, or the install is corrupted. Try reinstalling and/or upgrading to the latest version of your compiler.

Q: When trying to use endl to end a printed line, the compiler says end1 is an 'undeclared identifier'

Make sure you do not mistake the letter l (lower case L) in endl for the number 1. endl is all letters. Make sure your editor is using a font that makes clear the differences between the letter lower case L, upper case i, and the number 1. Also the letter capital o and the number zero can easily be confused in many non-programming fonts.

Visual Studio issues

Q: When compiling with Microsoft Visual C++, you get a C1010 fatal error, with an error message like "c:\vcprojects\test.cpp(263) :fatal error C1010: unexpected end of file while looking for precompiled header directive"

This error occurs when the Microsoft Visual C++ compiler is set to use precompiled headers but one (or more) of your C++ code files does not #include “stdafx.h” or #include “pch.h” as the first line of the code file.

Our suggested fix is to turn off precompiled headers, which we show how to do in lesson 0.7 -- Compiling your first program.

If you would like to keep precompiled headers turned on, to fix this problem, simply locate the file(s) producing the error (in the above error, test.cpp is the culprit), and add the following line at the very top of the file(s):

Older versions of Visual Studio use “stdafx.h” instead of “pch.h”, so if pch.h doesn’t resolve the issue, try stdafx.h.

Note that for programs with multiple files, every C++ code file needs to start with this line.

Alternatively, you can turn off precompiled headers.

Q: Visual Studio gives the following error: "1MSVCRTD.lib(exe_winmain.obj) : error LNK2019: unresolved external symbol [email protected] referenced in function "int __cdecl invoke_main(void)" ([email protected]@YAHXZ)"

You’ve likely created a Windows graphical application rather than a console application. Recreate your project, and make sure to create it as a Windows (or Win32) Console project.

Q: When I compile my program, I get a warnings about "Cannot find or open the PDB file"

This is a warning, not an error, so it shouldn’t impact your program. However, it is annoying. To fix it, go into the Debug menu -> Options and Settings -> Symbols, and check “Microsoft Symbol Server”.

Something else

Q: I have some other problem that I can't figure out. How can I get an answer quickly?

As you progress through the material, you’ll undoubtedly have questions or run into unexpected problems. What to do next depends on your problem. But in general, there are a few things you can try.

First, ask Google. Find a good way to phrase your question and do a Google search. If you have received an error message, paste the exact message into google using quotes.
Odds are someone has already asked the same question and there is an answer waiting for you.

If that fails, ask on a Q&A board. There are websites designed for programming questions and answers, like Stack Overflow. Try posting your question there. Remember to be thorough about what your problem is, and include all relevant information like what OS you’re on and what IDE you’re using.

0.9 -- Configuring your compiler: Build configurations
0.7 -- Compiling your first program

286 comments to 0.8 — A few common C++ problems

  • cmpj

    in code blocks
    on windoes where i compile it
    this is what i get

    "helloworld - Debug": The compiler's setup (GNU GCC Compiler) is invalid, so Code::Blocks cannot find/run the compiler.
    Probably the toolchain path within the compiler options is not setup correctly?! (Do you have a compiler installed?)
    Goto "Settings->Compiler...->Global compiler settings->GNU GCC Compiler->Toolchain executables" and fix the compiler's setup.
    Nothing to be done (all items are up-to-date).

    • Alex

      As the error message says, do you have a compiler installed? Code::Blocks comes in different configurations -- some of them don't come with compilers. If you're running on Windows, make sure you download the mingw version.

  • Maria

    but output screen still blink after writing these lines....

  • Daniel Ahn

    well i don't get what you mean by:
    Second, add the following code at the end of the main() function (right before the return statement):

    2cin.ignore(255, 'n');
    This will cause your program to wait for you to press a key before continuing, which will give you time to examine your program’s output before your compiler closes the console window.

    Other solutions, such as the commonly suggested system(“pause”) solution may only work on certain operating systems.

    i tried to put is just right before return0;
    just what ever but it shows bunch of error
    and when i press ctrl and F5 together it will stay but when I click debugging it closes immediately

  • James

    I see the responses here started back in 2007. It is now 2015. That's eight years... so where's the book?
    Thanks for the great tut.

  • Captain Obvlious

    Recommending the use of using namespace std; is itself a problem, especially if you are doing at global scope and definitely if you do it in a header file.

  • Nexus

    As an alternative (and sometimes better) solution for Problem 3:

    std::cout << "Hello World" << std::endl;

    This is good to use when you are using multiple namespaces (I know a bit of C++, I am just starting from the beginning to make sure I get everything), but for now it may be good just to type:

    using namespace std;

    As they suggest. I just wanted to put that out there so that people know about it before they get too solidified with the idea of using the already suggested solution.

    You can view a short video by about namespaces here:
    It is about 3 minutes long.

  • Hi. I am new to CPP. I used to have this problem of the output flashing and disappearing, but a friend told me to use clrscr() after declaring the variables and getch(); just before the closing braces of the program. Now, the output stays put until I press enter. I just want to know what exactly the getch() function does...
    I'd love it if you explained. :-)

    • TonyArra

      For anyone else interested in this question:

      clrscr() and getch() are part of the conio.h library (non-standard library that won't come with most compilers and is not available on Linux).

      clrscr() just clears the console screen.

      getch() is a variant of the standard getchar() function. getch() waits for the user to press any character on the keyboard. The function returns the character, but doesn't print the character to the screen like getchar() does. It also does not require the user to press the Enter key in order to submit the character (this is convenient because you no longer need to flush the standard input stream).

      On Linux, you can get similar functionality by installing the curse.h library.

  • Vignesh

    for all those using dev c++ , this code will work and pause you screen until you enter a character

    using namespace std;

    int main()
    cout<<"hello world!!";
    return 0;

    the getch(); is defined in conio.h and takes a character from input without printing to screen. you can see the output until you press a key.

    just saying even system("pause") will work except that it prints "Press any key to continue" .

  • mezz

    Would you say this tutorial would be improved if it was explicit in naming, e.g., instead of using using namespace std; using the "std::" reference? I'm just wondering because I'm being told it is OK, but better to future-proof and avoid any inherited name collisions.

  • zac123

    couldnt get this to stay open. using c++ 2010 express.

    after reading through the comments herei got it to work with this:

    // HelloWorld.cpp : Defines the entry point for the console application.
    #include "stdafx.h"
    using namespace std;
    int main()

    std::cout << "Hello world!" << std::endl;

    thanks for this brilliant web site. ive just started learning c++ sp this will be very useful!

  • viccos

    First I just wanted to say thank you so much for this site. You have really created something special here. As a completely self-taught IT professional I owe my living to people like you and this ranks amongst the best tutorials I have come across in any field.

    With that said I thought you might like to know about a pit-fall I... er... fell into.

    Having successfully run my program once I got excited and tried a few variations. I then found that my program had started blinking up for a fraction of a second and vanishing. I tried all of the things you suggested and then hit the web.

    Half an hour later I realised I was now pressing F5 instead of Control + F5 to run my program. Stupid error on my part but might be worth mentioning in the tutorial with an explanation of why you use Control+F5 rather than just F5 :)

  • Cameron

    whenever i try to compile my Code::Block logs say, "HelloWorld - Debug" uses an invalid compiler. Skipping... Nothing to be done.

    its annoying as can be, im positive its in the right directory for the compiler, and its using the g++ compiler. Im running the new patch for Mac OS X :/


  • GlassJoe

    Also, Why does the solution to the 3rd problem work? What exactly does the solution accomplish?-- You know, in a behind the scenes mechanical sense?
    (Sorry I missed my window of time for editing my previous post.)

    • Quinn

      When you declare "using namespace" you tell the compiler that, in the event that it cannot find the function or object in the global scope (the global namespace), that it should try placing the namespace(s) provided before in front of the function or object. For example, you can choose to either do it this way...

      Or this way...

      There's more information about namespaces, and the reasoning behind them, on the namespaces lesson of this site.

  • GlassJoe

    Ok, so I see that many people have had problems with running their .exe file rather than running the project straight from the IDE.
    My problem precludes this. How exactly do I link the .obj files to create the .exe? (I am using Visual C++ 2008.) I didn't see any instructions in the previous subchapter, and since I'm a newb I couldn't figure it out. Thanks.

    • Quinn

      You need to use your compilers Linker. I don't know what VC++ uses as a linker, to be honest. I always use gcc, so I couldn't help you on that one (heck, I'm on a Linux computer, so I wouldn't even be able to download VC++ to try it out). However, MSDN has some information on using the VC++ linker, called LINK. It should be as easy as navigating in the command prompt to the folder with your .obj files, then saying "link /OUT:MyProgName.exe MyObject1.obj MyObject2.obj".

      Though, then again, if you're using Visual Studio, there should be a very easy "Compile and run" button in there...

  • Teclo

    Sorry but I have no idea where I'm meant to put:
    cin.ignore(255, '\n');
    I don't know what you mean by "add the following code at the end of the main() function (right before the return statement)" since there isn't a ";" at the end of "main()", right? If I put the above lines of code right after main() I just get a bunch of errors. If I remove the three lines, it compiles properly but closes after outputting. Can you show those three lines of code within other code to show exactly how it should look please?

    • Teclo

      Sorry, I've figured it out now. I misread something on Wikipedia and ended up thinking that the return statement was ";". I'd better pay more attention in the future!

  • the easiest, simplest, and just plain best way to make a c++ program pause is to just put

    at the end of the main function.Note that in order for this to work you must have the statement

    at the top of the code and

    just before the main function.

    • Unfortunately this won't work if there are already characters in the cin input buffer. In that case, the cin.get() will just read the next char out of the buffer and not stop.

      That's the purpose of the other two lines -- to clear the input buffer so that cin.get() will stop to ask you for more input.

  • Juan

    Can I buy these tutorials on CD or something?
    Thanks for having these tutorials! I like it ;)

  • No I am not using:

    cin.ignore(255, 'n');

    Because I thought you said that code should be added only for users who are using Deviant, and not Visual Studio? Or Am I wrong?? Anyways I am using visual studio C++ 2008 and I have the code written exactly as you told in the tutorial:

    #include "stdafx.h"

    int main()
    std::cout << "Hello world!" << std::endl;
    return 0;

    Should I add those extra 3 lines of code?? Because I thought thats only for Deviant, anyways can you please respond back thx :)

    • I don't even know what Deviant is. :)

      If your program automatically closes after running it, then add those lines and it won't any more. They should work regardless of compiler, IDE, OS, etc...

  • I have the same problem as Christian, When i Open helloWorld from Debug: Start without debugging, the program opens fine, but then i try to run the .exe from the folder it opens for like 0.1 of a second and closes, what should i do?? please respond

    • I have no idea why it wouldn't be working. What compiler and OS are you using?

      • I am using microsoft visual C++ 2008 express edition, and my OS is Windows XP. The program opens fine when I run it from Debug: Start without debugging, it opens the way it should open and stays there until I close it, But when i run the .exe file from my HelloWorld folder in my VC2008Projects folder it opens for like 0.1 of a second and closes. What is the problem?? If you want I can take some screen shots to clerify more. Plz respond!

        • Are you using the following code at the bottom of main():


          • I had the same problem as Tassy (When I ran the .exe file)
            ... it only took me an hour to find this comment.

            Why does the program run in Microsoft Visual C++ 2008 Express Edition and produce a pause with the result showing in the cmd prompt window, BUT not when you run the .exe program?

            BTW: Great job with this tutorial.
            It's easy to understand and your responses to all our comments/questions is an awesome and appreciated committment. Thank you.

          • Thera

            I think I found the solution to his problem, because I ran across it just now too.

            It's a really simple thing, it's not even coding related:

            In the 2008 version, they changed around the hotkeys. So F5 is not 'run without debugging' but it's 'start debugging'. 'Run without debugging' has become ctrl+F5 instead.
            So someone pressing F5, as is recommended in the tutorial, will start debugging, in which case, for me at least, it doesn't work. However, choosing 'run without debugging' from the debug menu does help.

            Apparantly someone at miscrosoft thought that it would be more userfriendly to have debugging accessed more quickly...

            I hope this helps.

  • Howard

    im planning on learning cpp but one question is it any good if your not doing like visual programming i mean like gaming or should i rather learn java can u tell me some pros and cons for each.? thanks

    • I'm not a Java guy, so I couldn't fairly compare and contrast the languages. Do a google search and I'm sure you'll find plenty of people who are willing to make the comparison.

  • asdfk

    is it better to use getch ? =/ seems shorter to me

    • i'm a beginner too, but as i've tried compiling your program. There seems to be an error on "void main()"

      and the error is resolve as soon i changed it to int main()

      what's the difference?

      • Technically, main() is supposed to have return type int. However, many compilers will let you get away with returning type void instead (they do an implicit return 0 at the end of main). I guess you found one of the compilers that doesn't let you do that. :)

        It's generally a good idea to have main() return an int. It's guaranteed to be compatible across all compilers, whereas a return type of void on main() is not.

    • conio.h is not part of the standard C or C++ language, and many compilers don't support it. It may work on your compiler, but you should generally using it, as your code will not be properly compatible.

      • Connor

        I know this is an old post but...
        I'm an uber beginner but so far I've found that conio.h is excellent for 1 thing in particular -> grabbing user input without them having to hit enter, for instance:

        allows you to terminate without having to hit enter. _getch() simply grabs the input immediately from the buffer. However, there can be issues if there are still chars awaiting in the buffer...Alex, will the cin.clear() and cin.ignore(32767, 'n') work to clear the buffer before _getch()?

        • Alex

          I have no idea how cin and conio interact in a modern compiler. conio is an old dos/windows i/o library that is not part of the C++ standard and has long since been deprecated in favor of iostream.

  • Niels

    Another question.
    How does the compiler knows the location of the include files?

    • Generally your project will have a project directory or source directory that will be the home for your source code files by default. You can use relative pathing to include files in child or parent directories from there. Also, most (all?) compilers give you the option to add directories to your
      "include path" -- these directories will be searched if the compiler can't find a file in the current project directory. In this way, you can add 3rd party libraries to your include path and not have to copy the files directly into your projects when using them.

  • Niels

    I am beginning programming so I am curious about the identifiers used in include files.
    Should I learn which identifiers I can use from include files? Is it possible to list identifiers from include files and what
    they are doing (like cout in iostream.h)? Or is it just expierence to know which identifiers I can use? How do I know which
    file to include in my code when using an identifier?

    • It's sort of a mix of things -- if you wrote the headers yourself, you probably have an idea what identifiers they include. For things like the standard library, a good reference should tell you which headers to include for which things. For third party libraries, you'll either have to consult the documentation or actually look in the headers yourself.

  • I find some of these very helpful..thanks.

  • If you're using Dev-C++, you can put on the end of main function (before return 0;) system("PAUSE"); to don't close console window immediately. This command pause the program and wait to keypress. But I think that it works only in MS Windows.

  • Timon

    I made a comment here about endl, with a different name. Tiomon.. the infamous typo..

    I kept getting an error because instead of endl (lowercase L) I put end1 (ONE). I think you should put this up there since even though it's humiliating I took a "little" while trying to fix it (thanks to Google..) someone else might encounter the same thing I did.

    [ That's a great point. I'll add it to the FAQ. I added some additional advice in the answer to this issue. -Alex ]

  • Jason, good question. Here's a simple program that illustrates why cin >> myVariable is not the best way to pause:

    First, cin >> chIgnore ignores the enter key if the user does not provide any other input. You can verify this by hitting enter when the cin >> chIgnore line is being executed. On the other hand, cin.get() accepts the enter key as valid input.

    But perhaps more importantly is the second phenomena that occurs when more characters are placed into the input stream (cin) than are read out. When asked for a letter in the above program, enter more than one letter and watch what happens.

    Let's say you enter "abcde". cin >> buf[0] reads the 'a' character, but "bcde" are still left in the input stream. Consequently, when the code gets to cin >> chIgnore, it reads the waiting 'b' character out of the input stream and doesn't pause at all!

    The 3 step process is a little more foolproof. First, cin.clear() clears any errors the user may have caused by providing invalid input in the past. Second, cin.ignore(255, '\n') gets rid of up to 255 waiting characters in the input stream (or until a \n is encountered), which is almost always going to be enough to clear out the input stream. Finally, we use cin.get() to wait for a character. Since we just cleared the input stream, there are no characters waiting. Consequently, the program will wait for the user to enter something.

    In 99% of the cases you encounter, cin >> myVariable will probably work exactly as you expect. But since the 3 line method is generally more foolproof and isn't particularly burdensome to implement, I'd say it's the superior solution.

  • Jason

    In order to get the screen to pause before exiting the program, does the code:

    have any advantages over just using

    I have so much to learn. :)

  • foq

    Another great way to get a program to pause is to require a user input (cin). Using a menu-type interface that requires the user to select an option for "exiting" works well. I'm only a beginner, but for simple calculators that I've created, this works well.

  • Jason

    Problem 1: When executing a program from the IDE, the console window blinks and then closes immediately.

    The ide I'm using is Visual C .NET 2002. This ide has problem 1.

    To fix the problem I include the following command at the end of the main() function before the return statement.


    • Alex

      Unfortunately, this only works on the Windows operating system. The system() function tells the operating system to execute whatever the parameter is -- in this case, a command named "pause". On Windows, this waits for user input. On other operating systems (such as linux), the pause command does something else entirely. However, if you are only programming on Windows and not distributing your source code, you may find this an easier solution while learning.

Leave a Comment

Put all code inside code tags: [code]your code here[/code]