Hello World C++
Writing code can seem intimidating when you are first starting out.
1. Have Linux. If you are currently running Linux skip this step and go to step 2, other wise:
If you are not running Linux chances are you are running windows or mac. If you want you can use a virtual box to run Linux on top of your current OS or find a different tutorial for your own OS. To do this first download virtual box, then install what ever Linux distro you want. I recommend Ubuntu for beginners.
2. Make sure you have your compiler installed. Press ctrl+t to open your terminal and enter the following (note this only works on distros that use apt, use what ever package manager your distro uses):
sudo apt-get update && sudo apt-get install g++
3. Open up your text editor of choice, I recommend Sublime Text. You can always use the built in gui editor gedit or a terminal based editor such as vim or nano. For this tutorial I use nano.
4. Include the libraries we need by typing this:
#include <iostream>
5. Type the following on the next line to make it so you don't have to keep typing std later on in your code.
using namespace std;
6.Now we are going to declare our main function.
int main()
{
}
7. Now we put code inside of the brackets of the main function. Lets write Hello World! then make it go to the next line with \n or endl.
cout<<"Hello World!\n";
or
cout<<"Hello World!"<<endl;
8. This is all we want, it is looking for the program to return something because main is declared as an int. We will return 0.
return 0;
9. Your code should look like the following if you used the \n method. Notice the indent in the code after the parentheses. While this is not necessary for the compiler to understand what you want it to do, it helps you to keep your code organized.
#include <iostream>
usingnamespace std;
int main()
{
cout<<"Hello World\n";
return 0;
}
10. Comment your code! Right now you know what you mean, but later on you won't and will have no idea how your code works with out having to think about it. Comment your code using //!
#include <iostream> //library we are using
usingnamespace std; //so we don't have to type std in front of everything
int main() //main function
{
cout<<"Hello World\n"; //print Hello World! to the terminal
return 0; //have main return 0 as a value ending the program
}
11. Save your program as helloworld.cpp
12. Compile with the g++ compiler we opened before by entering the following into your terminal.
g++ helloworld.cpp -o helloworld
13. If no error messages came back it is time to run it type the following in your terminal:
./helloworld
This is where most C++ hello world tutorials end... Next you will want to learn how to create more functions and call them from your main function, variables, looping, then just throw some math in there and may be some objects or structs and you are well on your way.