C++ vs. Rust: Hello World

This is my first program in Rust, obviously, a “Hello World“! :)

Two ways of creating it:

1. Everything manually

a. Need to create a file with .rs extension. In my case: HelloWorld.rs

b. Write the actual program in that file:

// Hello World in Rust

/* 
 * Same multiline comment like in C
 */

fn main()
{
  println!("Hello world");
}

c. Go to the command line and compile the file with the rustc compiler

rustc HelloWorld.rs -o HelloWorld

d. Execute the binary file

./HelloWorld
Hello world

2. Using cargo.

a. cargo is the Rust package manager that helps you managing dependencies and also is useful in the build process. You can use it to create your program and compile it. So, we can create a new “cargo package“:

cargo new HelloWorld

b. That creates a new “cargo package” called “HelloWorld“: cargo new creates a new “HelloWorld” directory, that contains a Cargo.toml descriptor file and a src directory that contains a main.rs skeleton file that already contains a “Hello World” project similar to the one I wrote above:

fn main() {
    println!("Hello, world!");
}

c. To compile the package, we can build it using cargo too:

cd HelloWorld
cargo build

d. If everything is ok, a new directory called target is created and inside it, directories for debug or release builds (cargo build --release). Going to the debug folder we can run the HelloWorld executable.

3. “Hello World” content

The comments are similar to the C-like languages: // for simple line and /* */ for multiline comments.

The “fn” keyword identifies a block as a Rust function. All functions in Rust have a name and a set of arguments. The return type will be deduced automatically by the compiler.

main“, as in C, is the program entry point and is the function that is executed when you invoke the program from the command line.

println!” is a Rust macro that prints a line of the text specified. A Rust macro is a piece of code able to generate code by itself (metaprogramming).

This is it for now. I will continue writing about Rust while learning it. Thanks for reading!

4. Comparison with C++

This is the most similar implementation of “Hello world” in C++:

#include "fmt/core.h"

int main()
{
  fmt::print("Hello world\n");
}

I used libfmt to print the "Hello world” text to make both implementations as similar as possible.

Notice that Rust does not need any #include stuff. Actually Rust lets you import libraries in a modern way (similar to Java imports or C++20 modules) but println! is a macro included in the standard library, imported by default.

Function main() is also the program entry point in Rust, but it does not return anything, in C++, it MUST return an int, that, if not explicitly mentioned, it will return 0.

C++ “Hello world”

Ok, the most famous first program in any programming language is the ‘Hello World’ program, so I will explain how to create one in this post.

For my example, I will use ‘g++’ in a Linux environment, but ‘clang++’ works exactly the same way.

To write a ‘Hello World’ program in C++, you will need to create an empty file and name it with an appropriate extension (any name will do, for instance, HelloWorld.cpp). Common C++ file extensions include ‘.cpp’, ‘.cxx’, and ‘.cc’.

The compiler does not require the filename to match the name of any ‘class’ or other content inside the file. You can also store the file in any folder; there is no need to create it in a specific directory containing all the elements of a ‘package’ (like in Java).

Once you have created an empty HelloWorld.cpp file, you can open it in any text editor and start writing the following lines of code:

#include <iostream>
 
int main()
{
  std::cout << "Hello world\n";
}

Save the file, open a terminal, navigate to the folder where your file is located, and then enter the following command:

g++ HelloWorld.cpp -o HelloWorld

If you do not receive any messages after entering the command, congratulations! Your program has compiled successfully. Otherwise, there is an error in your code that you will need to fix before compiling again.

Once it compiles correctly, you will need to run the program. In a Linux/Unix environment, you do this by typing ./ followed by the program’s name:

./HelloWorld

And the program output should be:

Hello world

Understanding how all of this works

The C++ compilation process consists of three main steps:

  • Preprocessing: This step involves the preprocessor, which performs various text substitutions and transformations on your code before it is compiled.
  • Compilation: During this phase, your code is converted into machine code, with placeholders for calls to functions that reside in external libraries.
  • Linking: This step resolves those function calls by linking them to the actual functions in the libraries your program uses. If you do not specify any additional libraries (as in our example), your program will only be linked to the Standard Library, which comes with any C++ compiler.

#include

#include <iostream>

All lines starting with ‘#’ are called ‘preprocessor directives’. These are instructions that the preprocessor recognizes and executes.

#include tells the preprocessor to locate the file specified either inside quotes or between angle brackets and insert its content where the #include directive is used.

If the filename is enclosed in angle brackets (as in our case), the preprocessor searches for the file in a predefined directory that the compiler is aware of. For example, it will look for the file iostream in that directory. In a Linux environment, these files are typically located in a path similar to this one (I am using g++ 8.2):

/usr/include/c++/8

If the filename is declared between double quotes, it means the file will be in the current folder or in a folder explicitly specified when compiling the program.

iostream is the file that contains a lot of code allowing our programs to handle input and output. In our ‘Hello World’, we will need std::cout, which is defined in this file.

main function

int main()

When you invoke your program, the operating system needs to know which piece of code to execute. This code resides in the main function.

All functions must return something. For example, if you call a function sum that adds two numbers, it must return a value containing the result of the sum. So, the sum function must return an integer value (an int). Some old compilers allowed the main() function to return void (meaning ‘return nothing’), but the C++ standard specifies that main() must return an int value.

However, even if main() is declared to return an int, if you do not explicitly return anything, the compiler will not complain and will automatically return 0. Note that this behavior is exceptional and only allowed for the main() function.

The return value of the main() function indicates whether an error occurred. A return value of 0 means the program executed without errors, while a non-zero value indicates an error. The specific non-zero value depends entirely on the programmer’s design and error-handling mechanisms.

The program will continue running as long as the main() function is executing. Once its execution ends, the program terminates and returns the value to the operating system.

The body of any function is enclosed in curly braces.

std::cout

std::cout << "Hello world\n";

std::cout is a pre-existing object that represents command line output. The << operator essentially sends the text "Hello world\n" to the std::cout object, resulting in that text being displayed in the terminal.

The \n character sequence indicates a newline.

g++

g++ and clang are the most popular C++ compilers for Unix platforms today. You can replace one with the other almost without restrictions because clang was designed to be a drop-in replacement for g++.

When you say something like:

g++ HelloWorld.cpp

You are instructing the g++ compiler to go through the entire compilation process for the file HelloWorld.cpp. ‘Go through the entire compilation process’ in this case means running the preprocessor on the file, compiling it, linking it, and producing an executable.

Since I did not specify the name of the executable file in the command line example above, the g++ command generates a file called a.out in the current folder.

To specify the name of the file to be generated, you must invoke g++ with the -o option followed by the name of the executable file you want to create.

C++: First message

#include <iostream>
#include <string>
 
int main()
{
  std::string greeting = "Ifmmp!xpsme\"";
   
  for (std::string::const_iterator i = greeting.begin(); i != greeting.end(); ++i)
       std::cout << static_cast<char>((*i) - 1);
   
  std::cout << std::endl;
  return 0;
}

 Hello,

In this blog, I want to publish interesting information about C++ and related topics (object-oriented programming, generic programming, etc.). The goal is to provide useful and accurate information. Since I am passionate about these topics but far from being an expert, I would appreciate your help in improving the accuracy of each post I write. Your comments and suggestions will be greatly appreciated and will help me enhance the content of this blog day by day.

Welcome, and thank you for reading!