Separating code into modules
Header files in C++
Basically, I had given a test for a position at an autonomous driving start-up and got 2 questions, one was in python while the second was in c++. I was able to complete the first question easily but wasn’t able to attempt the second question. As a result, I decided to revise c++ and start working on it along with python. I have started taking the Modern C++ course from Stachniss Lab, currently working towards my second homework. I have written about my first homework:
What if we want to separate the interface from implementation? We can use header files for declaring functions, but what if we want to separate the function definition from the cpp file having the main function? We can use a separate cpp file for defining functions declared in the header file while a separate cpp file for the main function.
Let’s take the example of a function that basically prints “Hello World” on the screen. We want to have a header file for its declaration which would be named hello.h with the following code:
The first line tells the compiler to include the header file only once while the second line declares the required function.
Now we need the function definition but we want it separate from the cpp file containing the main function, so we define it in a cpp file named hello.cpp which is as follows:
Now, we want the main function to call the defined function but it should be separate from the hello world function definition, for which we will define it in main.cpp, which is as follows:
But, how to compile this, well first we need to compile the hello.cpp using the following command:
c++ -c hello.cpp -o hello.o
-c in the above command means that we only want to compile it, not link it, that is, we want to make a module out of it.
After the above command, we need the following command:
c++ -std=c++11 main.cpp hello.o -o main.o
The command tells the compiler to link the hello.o with main.cpp so that when the compiler sees the hello.h file being included in main.cpp, it can fetch the required information from the hello.o object. Now we can execute the program using ./main.o which should display “Hello World” on the screen.