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.

Advertisement

C++ “Hello world”

Ok, the most famous first program on any programming language is the “Hello world” program, so I will explain how to create one in this post.

In my example I will use “g++” in a Linux environment, but “clang++” works exactly the same.

To create a “Hello world” in C++, you need to create an empty file and give it a name with an extension (any name, for example HelloWorld.cpp); “cpp”, “cxx” or “cc” are well-known C++ file name extensions.

The compiler does not verify if the filename is equal to the name of the “class” or anything inside the file; the file can be stored on any folder too, you do not need to create it inside a special folder containing all stuff of a given “package” (à la Java), for example.

So, after creating an empty HelloWorld.cpp, you can open it using any text editor and start to write the following lines of code:

#include <iostream>

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

Save it, open a terminal, go to the folder where your file is located and there, enter this:

g++ HelloWorld.cpp -o HelloWorld

If after entering that command line you do not get any message, BE HAPPY! Your program compiled properly. Otherwise, you did some error in your code and you need to fix it and compile it again.

After compiling it properly, you need to execute the program. In a Linux/Unix environment, you do that writing the name of the program after a ./ :

./HelloWorld

And the program should show:

Hello world

Understanding how all of this worked

The compilation process in C++ has basically three steps:

  1. Passing your program through the "preprocessor"; an entity that performs several text transformations on your code before being compiled.
  2. The actual compilation process, that turns all your code into machine code with several calls to functions that are located in other libraries.
  3. The linking process, that binds the function calls with the actual functions in the libraries the program uses. If you do not specify anything (as in our case), your program will be linked only to the Standard Library that ships with any C++ compiler.

The parts of the program

#include

#include <iostream>

All things that start with "#" are called "preprocessor directives", that are instructions the preprocessor understands and executes.

#include tells to the preprocessor to look for the file named inside quotes or less-than and greater-than and put its content in the place the #include directive was invoked.

If the filename is inside less-than and greater-than characters (as in our case), the preprocessor will look for the file in a previously defined folder the compiler knows about. So, it will look for the file iostream in that folder. In a Linux environment, those files are generally 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 explictly mentioned while compiling the program.

iostream is the file that contains a lot of code that allows our programs to have data input and output. In our “Hello World”, we will need “std::cout” that is defined in this file.

main function
int main()

When you invoke your program, the operating system needs to know what piece of code it needs to execute. Such piece of code lives inside the function main.

All functions must return something, for example, if you call a function sum that sums two numbers, it must return a value containing the result of the sum. So, the function sum must return an integer value (an int). Some old compilers used to allow the function main() to return “void” (that means: “return nothing”) but the C++ standard specifies the main() function must return an int value.

Anyway, though this function is declared returning an int, if you do not return anything, the compiler does not complain about that and returns a 0. Notice that this behavior is exceptional and it is only allowed for the function main().

The return value of function main() specified if an error occurred or not. 0 means that no error occurred during the program executed; and a non-zero value means that an error occurred. The specific value being returned is completely depending on the programmers design and error mechanisms defined by them.

The program will be executed while the function main() is being executed. When its execution ends, the program automatically ends returning the return value to the Operating System.

The body of any function is declared inside two curly braces.

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

std::cout is a pre-existing object that represents the command line output. The “<<" is an operator that basically does, in this case, sends the text "Hello world\n" to the std::cout object, producing an output of such text in the terminal.

The \n character sequence means an end of line.

g++

g++ is the most popular C++ compiler for Unix platforms. These days clang has a lot of popularity and you can replace one to other because clang parameters are completely compatible to the g++ ones.

When you say something like:

g++ HelloWorld.cpp

You are instructing to the g++ compiler to go through all the compilation process for the file “HelloWorld.cpp”. “Go through all the compilation process” in this case means: Running the preprocessor on the file, compiling it, linking it and producing an executable.

Since in this command line in my example above I did not mention the name of the executable file, 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 and then the name of the executable file to be generated.