赞
踩
To write a C++ program inside an IDE, we typically start by creating a new project (we’ll show you how to do this in a bit). A project is a container that holds all of your source code files, images, data files, etc… that are needed to produce an executable (or library, website, etc…) that you can run or use. The project also saves various IDE, compiler, and linker settings, as well as remembering where you left off, so that when you reopen the project later, the state of the IDE can be restored to wherever you left off. When you choose to compile your program, all of the .cpp files in the project will get compiled and linked.
Each project corresponds to one program. When you’re ready to create a second program, you’ll either need to create a new project, or overwrite the code in an existing project (if you don’t want to keep it). Project files are generally IDE specific, so a project created for one IDE will need to be recreated in a different IDE.
Create a new project for each new program you write.
When you create a new project, you’ll generally be asked what type of project you want to create. All of the projects that we will create in this tutorial will be console projects. A console project means that we are going to create programs that can be run from the Windows, Linux, or Mac console.
By default, console applications have no graphical user interface (GUI), they print text to the console, read input from the keyboard, and are compiled into stand-alone executable files. This is perfect for learning C++, because it keeps the complexity to a minimum, and ensures things work on a wide variety of systems.
Don’t worry if you’ve never used a console before, or don’t know how to access it. We’ll compile and launch our programs through our IDEs (which will invoke the console when necessary).
When you create a new project for your program, many IDEs will automatically add your project to a “workspace” or a “solution” (the term varies by IDE). A workspace or solution is a container that can hold one or more related projects. For example, if you were writing a game and wanted to have a separate executable for single player and multiplayer, you’d need to create two projects. It wouldn’t make sense for both of these projects to be completely independent – after all, they are part of the same game. Mostly likely, each would be configured as a separate project within a single workspace/solution.
Although you can add multiple projects to a single solution, we generally recommend creating a new workspace or solution for each program, especially while learning. It’s simpler and there’s less chance of something going wrong.
Traditionally, the first program programmers write in a new language is the infamous hello world program, and we aren’t going to deprive you of that experience! You’ll thank us later. Maybe.
In large projects (those with many code files), precompiled headers can improve compilation speed by avoiding some redundant compilation that tends to occur in larger projects.
However, precompiled headers require extra work to use, and for small projects (such as those you’ll create in our tutorials) make little to no difference in compilation times.
For this reason, we recommend turning precompiled headers off initially, and only enabling them later if and when you find your compilation times suffering.
When a console program is run, the console window will open and any output from the program will be written into the console window.
When the program has finished running, most modern IDEs will keep the console open (until you press a key) so you can inspect the results of the program before continuing. However, some older IDEs will automatically close the console window when the program finishes running. This is generally not what you want.
If your IDE closes the console window automatically, the following two steps can be used to ensure the console pauses at end of the program.
First, add or ensure the following lines are near the top of your program:
#include <iostream>
#include <limits>
Second, add the following code at the end of the main() function (just before the return statement):
std::cin.clear(); // reset any error flags
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // ignore any characters in the input buffer until we find a newline
std::cin.get(); // get one more char from the user (waits for user to press enter)
This will cause your program to wait for the user to press enter before continuing (you may have to press enter twice), which will give you time to examine your program’s output before your IDE 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.
If the console window doesn’t open at all and your program doesn’t appear to be running, your anti-virus or anti-malware may also be blocking execution of the program. If that’s the case, try temporarily disabling your scanners and see if the problem resolves.
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.8 – 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.
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.
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):
#include "pch.h"
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.
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 a search engine. Find a good way to phrase your question and do a search. If you are searching an error message, paste in the exact error message using quotes (exclude any filenames or line numbers). 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.
A build configuration (also called a build target) is a collection of project settings that determines how your IDE will build your project. The build configuration typically includes things like what the executable will be named, what directories the IDE will look in for other code and library files, whether to keep or strip out debugging information, how much to have the compiler optimize your program, etc… Generally, you will want to leave these settings at their default values unless you have a specific reason to change something.
Use the debug build configuration when developing your programs. When you’re ready to release your executable to others, or want to test performance, use the release build configuration.
For Visual Studio users
There are multiple ways to switch between debug and release in Visual Studio. The easiest way is to set your selection directly from the Solution Configurations dropdown in the Standard Toolbar Options:
VS Solution Configurations Dropdown
Set it to Debug for now.
You can also access the configuration manager dialog by selecting Build menu > Configuration Manager, and change the active solution configuration.
Disable compiler extensions to ensure your programs (and coding practices) remain compliant with C++ standards and will work on any system.
To disable compiler extensions, right click on your project name in the Solution Explorer window, then choose Properties:
From the Project dialog, first make sure the Configuration field is set to All Configurations.
Then, click C/C++ > Language tab, and set Conformance mode to Yes (/permissive-) (if it is not already set to that by default).
These settings are applied on a per-project basis. You need to set them every time you create a new project, or create a template project with those settings once and use that to create new projects.
Don’t let warnings pile up. Resolve them as you encounter them (as if they were errors). Otherwise a warning about a serious issue may be lost amongst warnings about non-serious issues.
Turn your warning levels up to the maximum, especially while you are learning. It will help you identify possible issues.
To increase your warning levels, right click on your project name in the Solution Explorer window, then choose Properties:
From the Project dialog, first make sure the Configuration field is set to All Configurations.
Then select C/C++ > General tab and set Warning level to Level4 (/W4):
Note: Do not choose EnableAllWarnings (/Wall) or you will be buried in warnings generated by the C++ standard library.
It is also possible to tell your compiler to treat all warnings as if they were errors (in which case, the compiler will halt compilation if it finds any warnings). This is a good way to enforce the recommendation that you should fix all warnings (if you lack self-discipline, which most of us do).
Enable “Treat warnings as errors”. This will force you to resolve all issues causing warnings.
This website currently targets the C++17 standard, meaning our lessons and examples assume your compiler is C++17 capable. Some C++20 content is available for those with C++20 compatible compilers.
To take full advantage of all the lesson content, we recommend using the C++20 language standard if your compiler supports it. Using the C++17 language standard will also provide a good experience.
If your compiler doesn’t support C++17, we recommend upgrading to one that does. If this is not possible for some reason, you will need to skip some content, and alter some examples so that they will compile. This should not impact your overall experience too heavily (especially in the early lessons).
C++14 is the minimum language standard for a decent experience on this site.
As of the time of writing, Visual Studio 2022 defaults to C++14 capabilities, which does not allow for the use of newer features introduced in C++17 and C++20.
To use these newer features, you’ll need to enable a newer language standard. Unfortunately, there is currently no way to do this globally – you must do so on a project-by-project basis.
With Visual Studio, you will need to reselect your language standard every time you create a new project.
We recommend choosing the latest standard “ISO C++ Latest (/std:c++latest)”, which will ensure you can use as many features as your compiler supports.
Make sure you’re selecting the language standard from the dropdown menu (don’t type it out).
Having to reselect all of your settings options every time you create a new project is burdensome. Fortunately, most IDEs provide a way to export your settings. This is typically done by creating a new project template with the settings you want, and then selecting that project template when you create a new project.
In Visual Studio, this option is available via Project -> Export Template. Select “Project template”, add a name and optional description (e.g. C++20 console application), and then click “Finish”.
Next time you create a new project, you’ll see this template show up in your list of project templates.
Once you create a new project with this template, it may not open any files. You can open up your .cpp file in the Solution Explorer window by going to Solution -> -> Source Files -> .cpp.
Each C++ language standard is described by a standards document, which is a formal technical document that is the authoritative source for the rules and requirements of a given language standard. The standards document is not designed for learning – rather, it’s designed for compiler writers to be able to implement new language standards accurately. You will occasionally see people quoting the standards document when explaining how something works.
The approved C++ standards document for a given language standard is not available for free. There is a link to purchase the latest standard here.
When a new language standard is being developed, draft standards documents are published for review. These drafts are available online for free. The last draft standard before the approved standard is generally close enough to the official standard to use for most purposes. You can find the draft standards here.
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。