Showing
- 4-Templates/3b-hands-on.ipynb 5 additions, 6 deletions4-Templates/3b-hands-on.ipynb
- 4-Templates/4-Metaprogramming.ipynb 20 additions, 20 deletions4-Templates/4-Metaprogramming.ipynb
- 4-Templates/5-MoreAdvanced.ipynb 96 additions, 27 deletions4-Templates/5-MoreAdvanced.ipynb
- 5-UsefulConceptsAndSTL/0-main.ipynb 5 additions, 6 deletions5-UsefulConceptsAndSTL/0-main.ipynb
- 5-UsefulConceptsAndSTL/1-ErrorHandling.ipynb 209 additions, 68 deletions5-UsefulConceptsAndSTL/1-ErrorHandling.ipynb
- 5-UsefulConceptsAndSTL/1b-hands-on.ipynb 5 additions, 6 deletions5-UsefulConceptsAndSTL/1b-hands-on.ipynb
- 5-UsefulConceptsAndSTL/2-RAII.ipynb 8 additions, 6 deletions5-UsefulConceptsAndSTL/2-RAII.ipynb
- 5-UsefulConceptsAndSTL/3-Containers.ipynb 27 additions, 30 deletions5-UsefulConceptsAndSTL/3-Containers.ipynb
- 5-UsefulConceptsAndSTL/3b-hands-on.ipynb 5 additions, 6 deletions5-UsefulConceptsAndSTL/3b-hands-on.ipynb
- 5-UsefulConceptsAndSTL/4-AssociativeContainers.ipynb 18 additions, 13 deletions5-UsefulConceptsAndSTL/4-AssociativeContainers.ipynb
- 5-UsefulConceptsAndSTL/5-MoveSemantics.ipynb 125 additions, 96 deletions5-UsefulConceptsAndSTL/5-MoveSemantics.ipynb
- 5-UsefulConceptsAndSTL/6-SmartPointers.ipynb 85 additions, 37 deletions5-UsefulConceptsAndSTL/6-SmartPointers.ipynb
- 5-UsefulConceptsAndSTL/6b-hands-on.ipynb 5 additions, 6 deletions5-UsefulConceptsAndSTL/6b-hands-on.ipynb
- 5-UsefulConceptsAndSTL/7-Algorithms.ipynb 21 additions, 20 deletions5-UsefulConceptsAndSTL/7-Algorithms.ipynb
- 5-UsefulConceptsAndSTL/7b-hands-on.ipynb 5 additions, 6 deletions5-UsefulConceptsAndSTL/7b-hands-on.ipynb
- 6-InRealEnvironment/0-main.ipynb 5 additions, 6 deletions6-InRealEnvironment/0-main.ipynb
- 6-InRealEnvironment/1-SetUpEnvironment.ipynb 7 additions, 7 deletions6-InRealEnvironment/1-SetUpEnvironment.ipynb
- 6-InRealEnvironment/2-FileStructure.ipynb 47 additions, 47 deletions6-InRealEnvironment/2-FileStructure.ipynb
- 6-InRealEnvironment/2b-hands-on.ipynb 5 additions, 6 deletions6-InRealEnvironment/2b-hands-on.ipynb
- 6-InRealEnvironment/3-Compilers.ipynb 5 additions, 6 deletions6-InRealEnvironment/3-Compilers.ipynb
%% Cell type:markdown id: tags: | ||
# [Getting started in C++](./) - [Templates](./0-main.ipynb) - [Metaprogramming](./4-Metaprogramming.ipynb) | ||
%% Cell type:markdown id: tags: | ||
## Introduction | ||
We will no go very far in this direction: metaprogramming is really a very rich subset of C++ of its own, and one that is especially tricky to code. | ||
You can be a very skilled C++ developer and never use this; however it opens some really interesting prospects that can't be achieved easily (or at all...) without it. | ||
I recommend the reading of [Modern C++ design](../bibliography.ipynb#Modern-C++-Design) to get the gist of it: even if it relies upon older versions of C++ (and therefore some of its hand-made constructs are now in one form or another in modern C++ or STL) it is very insightful to understand the reasoning behind metaprogrammation. | ||
## Example: same action upon a collection of heterogeneous objects | ||
Let's say we want to put together in a same container multiple objects of heterogeneous type (one concrete case for which I have used that: reading an input data file with each entry is handled differently by a dedicated object). | ||
In C++11, `std::tuple` was introduced for that purpose: | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
#include <tuple> | ||
std::tuple<int, std::string, double, float, long> tuple = | ||
std::make_tuple(5, "hello", 5., 3.2f, -35l); | ||
``` | ||
%% Cell type:markdown id: tags: | ||
What if we want to apply the same treatment to all of the entries? | ||
%% Cell type:markdown id: tags: | ||
In more usual containers, we would just write a `for` loop, but this is not an option here: to access the `I`-th element of the tuple syntax is `std::get<I>`, so `I` has to be known at compiled time... which is not the case for the mutable variable used in a typical `for` loop! | ||
%% Cell type:markdown id: tags: | ||
Let's roll with just printing each of them: | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
#include <iostream> | ||
{ | ||
std::cout << std::get<0>(tuple) << std::endl; | ||
std::cout << std::get<1>(tuple) << std::endl; | ||
std::cout << std::get<2>(tuple) << std::endl; | ||
std::cout << std::get<3>(tuple) << std::endl; | ||
std::cout << std::get<4>(tuple) << std::endl; | ||
} | ||
``` | ||
%% Cell type:markdown id: tags: | ||
The treatment was rather simple here, but the code was duplicated manually for each of them. **Metaprogramming** is the art of making the compiler generate by itself the whole code. | ||
The syntax relies heavily on templates, and those of you familiar with functional programming will feel at ease here: | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
#include <iostream> | ||
template <std::size_t IndexT, std::size_t TupleSizeT> | ||
struct PrintTuple | ||
{ | ||
template<class TupleT> // I'm lazy I won't put there std::tuple<int, std::string, double, float, long> again... | ||
static void Do(const TupleT& tuple) | ||
{ | ||
std::cout << std::get<IndexT>(tuple) << std::endl; | ||
PrintTuple<IndexT + 1ul, TupleSizeT>::Do(tuple); // that's the catch: call recursively the next one! | ||
} | ||
}; | ||
``` | ||
%% Cell type:markdown id: tags: | ||
A side reminder here: we need to use a combo of template specialization of `struct` and static method here to work around the fact template specialization of functions is not possible (see [here](2-Specialization.ipynb#Mimicking-the-partial-template-specialization-for-functions) for more details) | ||
%% Cell type:markdown id: tags: | ||
You may see the gist of it, but there is still an issue: the recursivity goes to the infinity... (don't worry your compiler will yell before that!). So you need a specialization to stop it - you may see now why I used a class template and not a function! | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
template <std::size_t TupleSizeT> | ||
struct PrintTuple<TupleSizeT, TupleSizeT> | ||
{ | ||
template<class TupleT> | ||
static void Do(const TupleT& tuple) | ||
{ | ||
// Do nothing! | ||
} | ||
}; | ||
``` | ||
%% Cell type:markdown id: tags: | ||
With that, the code is properly generated: | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
{ | ||
std::tuple<int, std::string, double, float, long> tuple = | ||
std::make_tuple(5, "hello", 5., 3.2f, -35l); | ||
PrintTuple<0, std::tuple_size<decltype(tuple)>::value>::Do(tuple); | ||
} | ||
``` | ||
%% Cell type:markdown id: tags: | ||
Of course, the call is not yet very easy: it's cumbersome to have to explicitly reach the tuple size... But as often in C++ an extra level of indirection may lift this issue: | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
template<class TupleT> | ||
void PrintTupleWrapper(const TupleT& t) | ||
{ | ||
PrintTuple<0, std::tuple_size<TupleT>::value>::Do(t); | ||
} | ||
``` | ||
%% Cell type:markdown id: tags: | ||
And then the call may be simply: | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
{ | ||
std::tuple<int, std::string, double, float, long> tuple = std::make_tuple(5, "hello", 5., 3.2f, -35l); | ||
PrintTupleWrapper(tuple); | ||
} | ||
``` | ||
%% Cell type:markdown id: tags: | ||
In fact, my laziness earlier when I used a template argument rather than the exact tuple type pays now as this function may be used with any tuple (or more precisely with any tuple for which all elements comply with `operator<<`): | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
{ | ||
int a = 5; | ||
std::tuple<std::string, int*> tuple = std::make_tuple("Hello", &a); | ||
PrintTupleWrapper(tuple); | ||
} | ||
``` | ||
%% Cell type:markdown id: tags: | ||
## Slight improvement with C++ 17 `if constexpr` | ||
With C++ 17 compile-time check `if constexpr`, you may even do the same with much less boilerplate: | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
#include <iostream> | ||
template <std::size_t IndexT, class TupleT> | ||
void PrintTupleIfConstexpr(const TupleT& tuple) | ||
{ | ||
constexpr auto size = std::tuple_size<TupleT>(); | ||
static_assert(IndexT <= size); | ||
if constexpr (IndexT < size) | ||
{ | ||
std::cout << std::get<IndexT>(tuple) << std::endl; | ||
PrintTupleIfConstexpr<IndexT + 1, TupleT>(tuple); | ||
} | ||
}; | ||
``` | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
template<class TupleT> | ||
void PrintTupleIfConstexprWrapper(const TupleT& tuple) | ||
{ | ||
PrintTupleIfConstexpr<0ul>(tuple); | ||
} | ||
``` | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
{ | ||
std::tuple<int, std::string, double, float, long> tuple = std::make_tuple(5, "hello", 5., 3.2f, -35l); | ||
PrintTupleIfConstexprWrapper(tuple); | ||
} | ||
``` | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
{ | ||
int a = 5; | ||
std::tuple<std::string, int*> tuple = std::make_tuple("Hello", &a); | ||
PrintTupleIfConstexprWrapper(tuple); | ||
} | ||
``` | ||
%% Cell type:markdown id: tags: | ||
The gist of it remains the same (it amounts to a recursive call) but the compile-time check makes us avoid entirely the use of the stopping specialization and the use of a struct with `static` method. | ||
%% Cell type:markdown id: tags: | ||
## `std::apply` | ||
Another option provided by C++ 17 is to use `std::apply`, which purpose is to apply upon all elements of a same tuple a same operation. | ||
[Cppreference](https://en.cppreference.com/w/cpp/utility/apply) provides a snippet that solves the exact problem we tackled above in a slightly different way: they wrote a generic overload of `operator<<` for any instance of a `std::tuple` object. | ||
I have simplified somehow their snippet as they complicated a bit the reading with unrelated niceties to handle the comma separators. | ||
Don't bother if you do not understand all of it: | ||
- The weird `...` syntax is for variadic templates, that we will present [briefly in next notebook](../5-MoreAdvanced.ipynb#Variadic-templates). Sorry we avoid as much as possible to refer to future stuff in the training session, but current paragraph is a late addition and doesn't mesh completely well with the structure of this document. You just have to know it's a way to handle a variable number of arguments (here template arguments of `std::tuple`). | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
template<typename... Ts> | ||
std::ostream& operator<<(std::ostream& os, std::tuple<Ts...> const& theTuple) | ||
{ | ||
std::apply | ||
( | ||
[&os](Ts const&... tupleArgs) | ||
{ | ||
((os << tupleArgs << std::endl), ...); | ||
}, theTuple | ||
); | ||
return os; | ||
} | ||
``` | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
std::cout << tuple << std::endl; | ||
``` | ||
%% Cell type:markdown id: tags: | ||
# Bonus: metaprogramming Fibonacci | ||
In [notebook about constexpr](../1-ProceduralProgramming/7-StaticAndConstexpr.ipynb), I said implementing Fibonacci series before C++ 11 involved metaprogramming; here is an implementation (much more wordy than the `constexpr` one): | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
template<std::size_t N> | ||
struct Fibonacci | ||
{ | ||
static std::size_t Do() | ||
{ | ||
return Fibonacci<N-1>::Do() + Fibonacci<N-2>::Do(); | ||
} | ||
}; | ||
``` | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
// Don't forget the specialization for 0 and 1! | ||
template<> | ||
struct Fibonacci<0ul> | ||
{ | ||
static std::size_t Do() | ||
{ | ||
return 0ul; | ||
} | ||
}; | ||
template<> | ||
struct Fibonacci<1ul> | ||
{ | ||
static std::size_t Do() | ||
{ | ||
return 1ul; | ||
} | ||
}; | ||
``` | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
#include <iostream> | ||
std::cout << Fibonacci<5ul>::Do() << std::endl; | ||
std::cout << Fibonacci<10ul>::Do() << std::endl; | ||
``` | ||
%% Cell type:markdown id: tags: | ||
And if the syntax doesn't suit you... you could always add an extra level of indirection to remove the `::Do()` part: | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
template<std::size_t N> | ||
std::size_t FibonacciWrapper() | ||
{ | ||
return Fibonacci<N>::Do(); | ||
} | ||
``` | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
#include <iostream> | ||
std::cout << FibonacciWrapper<5ul>() << std::endl; | ||
std::cout << FibonacciWrapper<10ul>() << std::endl; | ||
``` | ||
%% Cell type:markdown id: tags: | ||
As you can see, in some cases `constexpr` really alleviates some tedious boilerplate... | ||
It should be noticed that although these computations really occur at compile time, they aren't nonetheless recognized automatically as `constexpr`: | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
constexpr auto fibo_5 = FibonacciWrapper<5ul>(); // COMPILATION ERROR! | ||
``` | ||
%% Cell type:markdown id: tags: | ||
To fix that, you need to declare `constexpr`: | ||
- Each of the `Do` static method (`static constexpr std::size_t Do()`) | ||
- The `FibonacciWrapper` function (`template<std::size_t N> constexpr std::size_t FibonacciWrapper()`) | ||
So in this specific case you should really go with the much less wordy and more expressive expression with `constexpr` given in [aforementioned notebook](../1-ProceduralProgramming/7-StaticAndConstexpr.ipynb) | ||
%% Cell type:markdown id: tags: | ||
[© Copyright](../COPYRIGHT.md) | ||
... | ... |
%% Cell type:markdown id: tags: | ||
# [Getting started in C++](./) - [Templates](./0-main.ipynb) - [Metaprogramming](./4-Metaprogramming.ipynb) | ||
%% Cell type:markdown id: tags: | ||
## Introduction | ||
We will no go very far in this direction: metaprogramming is really a very rich subset of C++ of its own, and one that is especially tricky to code. | ||
You can be a very skilled C++ developer and never use this; however it opens some really interesting prospects that can't be achieved easily (or at all...) without it. | ||
I recommend the reading of [Modern C++ design](../bibliography.ipynb#Modern-C++-Design) to get the gist of it: even if it relies upon older versions of C++ (and therefore some of its hand-made constructs are now in one form or another in modern C++ or STL) it is very insightful to understand the reasoning behind metaprogrammation. | ||
## Example: same action upon a collection of heterogeneous objects | ||
Let's say we want to put together in a same container multiple objects of heterogeneous type (one concrete case for which I have used that: reading an input data file with each entry is handled differently by a dedicated object). | ||
In C++11, `std::tuple` was introduced for that purpose: | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
#include <tuple> | ||
std::tuple<int, std::string, double, float, long> tuple = | ||
std::make_tuple(5, "hello", 5., 3.2f, -35l); | ||
``` | ||
%% Cell type:markdown id: tags: | ||
What if we want to apply the same treatment to all of the entries? | ||
%% Cell type:markdown id: tags: | ||
In more usual containers, we would just write a `for` loop, but this is not an option here: to access the `I`-th element of the tuple syntax is `std::get<I>`, so `I` has to be known at compiled time... which is not the case for the mutable variable used in a typical `for` loop! | ||
%% Cell type:markdown id: tags: | ||
Let's roll with just printing each of them: | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
#include <iostream> | ||
{ | ||
std::cout << std::get<0>(tuple) << std::endl; | ||
std::cout << std::get<1>(tuple) << std::endl; | ||
std::cout << std::get<2>(tuple) << std::endl; | ||
std::cout << std::get<3>(tuple) << std::endl; | ||
std::cout << std::get<4>(tuple) << std::endl; | ||
} | ||
``` | ||
%% Cell type:markdown id: tags: | ||
The treatment was rather simple here, but the code was duplicated manually for each of them. **Metaprogramming** is the art of making the compiler generate by itself the whole code. | ||
The syntax relies heavily on templates, and those of you familiar with functional programming will feel at ease here: | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
#include <iostream> | ||
template <std::size_t IndexT, std::size_t TupleSizeT> | ||
struct PrintTuple | ||
{ | ||
template<class TupleT> // I'm lazy I won't put there std::tuple<int, std::string, double, float, long> again... | ||
static void Do(const TupleT& tuple) | ||
{ | ||
std::cout << std::get<IndexT>(tuple) << std::endl; | ||
PrintTuple<IndexT + 1ul, TupleSizeT>::Do(tuple); // that's the catch: call recursively the next one! | ||
} | ||
}; | ||
``` | ||
%% Cell type:markdown id: tags: | ||
A side reminder here: we need to use a combo of template specialization of `struct` and static method here to work around the fact template specialization of functions is not possible (see [here](2-Specialization.ipynb#Mimicking-the-partial-template-specialization-for-functions) for more details) | ||
%% Cell type:markdown id: tags: | ||
You may see the gist of it, but there is still an issue: the recursivity goes to the infinity... (don't worry your compiler will yell before that!). So you need a specialization to stop it - you may see now why I used a class template and not a function! | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
template <std::size_t TupleSizeT> | ||
struct PrintTuple<TupleSizeT, TupleSizeT> | ||
{ | ||
template<class TupleT> | ||
static void Do(const TupleT& tuple) | ||
{ | ||
// Do nothing! | ||
} | ||
}; | ||
``` | ||
%% Cell type:markdown id: tags: | ||
With that, the code is properly generated: | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
{ | ||
std::tuple<int, std::string, double, float, long> tuple = | ||
std::make_tuple(5, "hello", 5., 3.2f, -35l); | ||
PrintTuple<0, std::tuple_size<decltype(tuple)>::value>::Do(tuple); | ||
} | ||
``` | ||
%% Cell type:markdown id: tags: | ||
Of course, the call is not yet very easy: it's cumbersome to have to explicitly reach the tuple size... But as often in C++ an extra level of indirection may lift this issue: | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
template<class TupleT> | ||
void PrintTupleWrapper(const TupleT& t) | ||
{ | ||
PrintTuple<0, std::tuple_size<TupleT>::value>::Do(t); | ||
} | ||
``` | ||
%% Cell type:markdown id: tags: | ||
And then the call may be simply: | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
{ | ||
std::tuple<int, std::string, double, float, long> tuple = std::make_tuple(5, "hello", 5., 3.2f, -35l); | ||
PrintTupleWrapper(tuple); | ||
} | ||
``` | ||
%% Cell type:markdown id: tags: | ||
In fact, my laziness earlier when I used a template argument rather than the exact tuple type pays now as this function may be used with any tuple (or more precisely with any tuple for which all elements comply with `operator<<`): | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
{ | ||
int a = 5; | ||
std::tuple<std::string, int*> tuple = std::make_tuple("Hello", &a); | ||
PrintTupleWrapper(tuple); | ||
} | ||
``` | ||
%% Cell type:markdown id: tags: | ||
## Slight improvement with C++ 17 `if constexpr` | ||
With C++ 17 compile-time check `if constexpr`, you may even do the same with much less boilerplate: | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
#include <iostream> | ||
template <std::size_t IndexT, class TupleT> | ||
void PrintTupleIfConstexpr(const TupleT& tuple) | ||
{ | ||
constexpr auto size = std::tuple_size<TupleT>(); | ||
static_assert(IndexT <= size); | ||
if constexpr (IndexT < size) | ||
{ | ||
std::cout << std::get<IndexT>(tuple) << std::endl; | ||
PrintTupleIfConstexpr<IndexT + 1, TupleT>(tuple); | ||
} | ||
}; | ||
``` | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
template<class TupleT> | ||
void PrintTupleIfConstexprWrapper(const TupleT& tuple) | ||
{ | ||
PrintTupleIfConstexpr<0ul>(tuple); | ||
} | ||
``` | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
{ | ||
std::tuple<int, std::string, double, float, long> tuple = std::make_tuple(5, "hello", 5., 3.2f, -35l); | ||
PrintTupleIfConstexprWrapper(tuple); | ||
} | ||
``` | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
{ | ||
int a = 5; | ||
std::tuple<std::string, int*> tuple = std::make_tuple("Hello", &a); | ||
PrintTupleIfConstexprWrapper(tuple); | ||
} | ||
``` | ||
%% Cell type:markdown id: tags: | ||
The gist of it remains the same (it amounts to a recursive call) but the compile-time check makes us avoid entirely the use of the stopping specialization and the use of a struct with `static` method. | ||
%% Cell type:markdown id: tags: | ||
## `std::apply` | ||
Another option provided by C++ 17 is to use `std::apply`, which purpose is to apply upon all elements of a same tuple a same operation. | ||
[Cppreference](https://en.cppreference.com/w/cpp/utility/apply) provides a snippet that solves the exact problem we tackled above in a slightly different way: they wrote a generic overload of `operator<<` for any instance of a `std::tuple` object. | ||
I have simplified somehow their snippet as they complicated a bit the reading with unrelated niceties to handle the comma separators. | ||
Don't bother if you do not understand all of it: | ||
- The weird `...` syntax is for variadic templates, that we will present [briefly in next notebook](../5-MoreAdvanced.ipynb#Variadic-templates). Sorry we avoid as much as possible to refer to future stuff in the training session, but current paragraph is a late addition and doesn't mesh completely well with the structure of this document. You just have to know it's a way to handle a variable number of arguments (here template arguments of `std::tuple`). | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
template<typename... Ts> | ||
std::ostream& operator<<(std::ostream& os, std::tuple<Ts...> const& theTuple) | ||
{ | ||
std::apply | ||
( | ||
[&os](Ts const&... tupleArgs) | ||
{ | ||
((os << tupleArgs << std::endl), ...); | ||
}, theTuple | ||
); | ||
return os; | ||
} | ||
``` | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
std::cout << tuple << std::endl; | ||
``` | ||
%% Cell type:markdown id: tags: | ||
# Bonus: metaprogramming Fibonacci | ||
In [notebook about constexpr](../1-ProceduralProgramming/7-StaticAndConstexpr.ipynb), I said implementing Fibonacci series before C++ 11 involved metaprogramming; here is an implementation (much more wordy than the `constexpr` one): | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
template<std::size_t N> | ||
struct Fibonacci | ||
{ | ||
static std::size_t Do() | ||
{ | ||
return Fibonacci<N-1>::Do() + Fibonacci<N-2>::Do(); | ||
} | ||
}; | ||
``` | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
// Don't forget the specialization for 0 and 1! | ||
template<> | ||
struct Fibonacci<0ul> | ||
{ | ||
static std::size_t Do() | ||
{ | ||
return 0ul; | ||
} | ||
}; | ||
template<> | ||
struct Fibonacci<1ul> | ||
{ | ||
static std::size_t Do() | ||
{ | ||
return 1ul; | ||
} | ||
}; | ||
``` | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
#include <iostream> | ||
std::cout << Fibonacci<5ul>::Do() << std::endl; | ||
std::cout << Fibonacci<10ul>::Do() << std::endl; | ||
``` | ||
%% Cell type:markdown id: tags: | ||
And if the syntax doesn't suit you... you could always add an extra level of indirection to remove the `::Do()` part: | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
template<std::size_t N> | ||
std::size_t FibonacciWrapper() | ||
{ | ||
return Fibonacci<N>::Do(); | ||
} | ||
``` | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
#include <iostream> | ||
std::cout << FibonacciWrapper<5ul>() << std::endl; | ||
std::cout << FibonacciWrapper<10ul>() << std::endl; | ||
``` | ||
%% Cell type:markdown id: tags: | ||
As you can see, in some cases `constexpr` really alleviates some tedious boilerplate... | ||
It should be noticed that although these computations really occur at compile time, they aren't nonetheless recognized automatically as `constexpr`: | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
constexpr auto fibo_5 = FibonacciWrapper<5ul>(); // COMPILATION ERROR! | ||
``` | ||
%% Cell type:markdown id: tags: | ||
To fix that, you need to declare `constexpr`: | ||
- Each of the `Do` static method (`static constexpr std::size_t Do()`) | ||
- The `FibonacciWrapper` function (`template<std::size_t N> constexpr std::size_t FibonacciWrapper()`) | ||
So in this specific case you should really go with the much less wordy and more expressive expression with `constexpr` given in [aforementioned notebook](../1-ProceduralProgramming/7-StaticAndConstexpr.ipynb) | ||
%% Cell type:markdown id: tags: | ||
[© Copyright](../COPYRIGHT.md) | ||
... | ... |
%% Cell type:markdown id: tags: | ||
# [Getting started in C++](./) - [C++ in a real environment](./0-main.ipynb) - [Set up environment](./1-SetUpEnvironment.ipynb) | ||
%% Cell type:markdown id: tags: | ||
## Introduction | ||
I will present here briefly how to set up a minimal development environment... only in Unix-like systems: sorry for Windows developers, but I have never set up a Windows environment for development. You may have a look at WSL, which is gaining traction and enables you to use Linux inside Windows. | ||
This will explain installation for two mainstreams compilers: [GNU compiler for C++](https://en.wikipedia.org/wiki/GNU_Compiler_Collection) and [clang++](https://en.wikipedia.org/wiki/Clang). | ||
## Installing a compiler | ||
**Note:** Compilers themselves will be addressed more in depth in an [upcoming notebook](3-Compilers.ipynb). | ||
### Ubuntu / Debian | ||
%% Cell type:markdown id: tags: | ||
#### Clang | ||
To install `clang` you need to specify explicitly the required version, e.g.: | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
// In a terminal | ||
sudo apt-get install -y clang++-13 | ||
``` | ||
%% Cell type:markdown id: tags: | ||
#### Default g++ | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
// In a terminal | ||
sudo apt-get install -y g++ | ||
``` | ||
%% Cell type:markdown id: tags: | ||
#### More recent gcc | ||
However, Ubuntu is rather conservative and the version you get might be a bit dated and it might be problematic if you intend to use the bleeding-edged features from the latest C++ standard (even if it's now better than what it used to be). | ||
In February 2024, default Ubuntu provided gcc 12; if you want gcc 13 you need to use the following [PPA](https://launchpad.net/ubuntu/+ppas): | ||
(_disclaimer_: the instructions below have been tested in a Docker image - with `RUN` instead of `sudo` of course - so all the lines might not be necessary in a full-fledged Ubuntu distro) | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
// In a terminal | ||
// Update the Ubuntu environment | ||
sudo apt-get update && sudo apt-get upgrade -y -q && sudo apt-get dist-upgrade -y -q && sudo apt-get -y -q autoclean && sudo apt-get -y -q autoremove) | ||
// To enable `add-apt-repository` command; probably not required in a full-fledged installation | ||
// but you will need it in a Docker image for instance | ||
sudo apt-get install --no-install-recommends -y software-properties-common gpg-agent wget | ||
// Adding PPA and making its content available to `apt`. | ||
sudo add-apt-repository ppa:ubuntu-toolchain-r/test | ||
sudo apt-get update -y | ||
// Installing the more recent gcc | ||
sudo apt-get install -y g++-13 | ||
``` | ||
%% Cell type:markdown id: tags: | ||
And to tell the system which version to use, the command is: | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
// In a terminal | ||
sudo update-alternatives --install /usr/bin/g++ g++ /usr/bin/g++-13 100 | ||
``` | ||
%% Cell type:markdown id: tags: | ||
More realistically, you will install gcc and perhaps gfortran as well; the following command make sure all are kept consistent (you do not want to mesh gcc 12 with g++ 13 for instance...): | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
// In a terminal | ||
sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-13 100 | ||
--slave /usr/bin/g++ g++ /usr/bin/g++-13 | ||
--slave /usr/bin/gfortran gfortran /usr/bin/gfortran-13 | ||
``` | ||
%% Cell type:markdown id: tags: | ||
### Fedora | ||
For development purposes I rather like Fedora, which provides more recent versions than Ubuntu and also a simple clang installation. | ||
%% Cell type:markdown id: tags: | ||
#### g++ | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
// In a terminal | ||
sudo dnf install -y gcc gcc-c++ gcc-gfortran | ||
``` | ||
%% Cell type:markdown id: tags: | ||
#### clang++ | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
// In a terminal | ||
sudo dnf install -y clang | ||
``` | ||
%% Cell type:markdown id: tags: | ||
### macOS | ||
* Install XCode from the AppStore | ||
* Install if requested the command line tools | ||
This will install _Apple Clang_ which is a customized version of `clang`. Unfortunately, Apple stopped providing the version of mainstream clang it is built upon; it's therefore more difficult to check if a new standard feature is already supported or not. | ||
It is also possible to install gcc on macOS; I personally use [Homebrew](https://brew.sh) to do so. However using it is not always reliable (on STL side at least - see below), especially shortly after a new version of XCode / Command Line Tools has been published; I would advise to use primarily clang. | ||
%% Cell type:markdown id: tags: | ||
## STL | ||
Besides the compiler, you may also choose which implementation of the STL you want to use. There are two mainstream choices: | ||
- `libstdc++`, which is the STL provided along gcc by GNU. This is the default choice for many Linux distro, and there is a good chance the binaries, libraries and share libraries in your package system were compiled with this one. | ||
- `libc++`, which is the STL provided along clang by LLVM. It is the default choice on macOS, and was until recently a pain to use with Ubuntu (according to Laurent it is much better now in Ubuntu 20.04 and more recent versions). | ||
Both are pretty solid choices: | ||
- Going with `libstdc++` is not a bad idea if you're using with your code libraries from your package manager that use this STL implementation (likely in a Linux distro). | ||
- Going with `libc++` along with clang++ seems rather natural as well. | ||
%% Cell type:markdown id: tags: | ||
Just a note for compatibility: `libc++` tends to provide more `include` directive in its header files than `libstdc++`. So don't be astonished if your code compiles well with `libc++` but complains about an unknown symbol from STL with `libstdc++` (and the patch is simply to use the missing include - a tool such as IncludeWhatYouUse would have underlined the missing include even when using `libc++`). | ||
%% Cell type:markdown id: tags: | ||
## Editor | ||
%% Cell type:markdown id: tags: | ||
You will need a [source code editor](https://en.wikipedia.org/wiki/Source_code_editor) to write your code; usually your system will provide a very basic one and you may be able to install another on your own. | ||
From my experience, there are essentially two types of developers: | ||
- Those that revel in using [VIM](https://en.wikipedia.org/wiki/Vim_(text_editor)) **or** [emacs](https://en.wikipedia.org/wiki/Emacs), which are lightweight editors that have been around for decades and are rather powerful once you've climbed a (very) steep learning curve. | ||
- Those that will like [integrated development environment](https://en.wikipedia.org/wiki/Integrated_development_environment) more, which provides more easily some facilities (that can often be configured the hard way in the aforementioned venerable text editors) but are more resource-intensive. | ||
I suggest you take whichever you're the most comfortable with and don't bother about the zealots that tell you their way is absolutely the best one. | ||
_Vim_ and _emacs_ are often either already installed or available easily with a distribution package (_apt_, _dnf_, etc...); for IDEs here are few of them: | ||
* [Visual Studio Code](https://code.visualstudio.com/), which gained traction in last few years and is one of the most sizeable GitHub project. This is an open-source and multi-platform editor maintained by Microsoft, not to be confused with [Visual Studio](https://visualstudio.microsoft.com/?rr=https%3A%2F%2Fwww.google.com%2F) - also provided by Microsoft on Windows (and with a fee). | ||
* [CLion](https://www.jetbrains.com/clion/) by JetBrains is also a rising star in IDEs; a free version is available for students (you may know PyCharm by the same company) | ||
* [Eclipse CDT](https://www.eclipse.org/cdt/) and [NetBeans](https://netbeans.org/) are other IDEs with more mileage. | ||
* [QtCreator](https://www.qt.io/qt-features-libraries-apis-tools-and-ide) is not just for Qt edition and might be used as a C++ IDE as well. | ||
* [XCode](https://developer.apple.com/xcode) is the editor provided by Apple on macOS. | ||
* [KDevelop](https://www.kdevelop.org/) is the IDE from the KDE project. | ||
* [JupyterLab](https://jupyter.org/) this very same notebook lab can be used as IDE after the last improvements and extensions added, [see this](https://towardsdatascience.com/jupyter-is-now-a-full-fledged-ide-c99218d33095) and how include the [VS Code Monaco Editor](https://imfing.medium.com/bring-vs-code-to-your-jupyterlab-187e59dd1c1b). I wouldn't advise it but if you're really keen to roll with it. | ||
%% Cell type:markdown id: tags: | ||
## Software configuration manager | ||
A [software configuration manager](https://en.wikipedia.org/wiki/Software_configuration_management), sometimes abbreviated as **SCM**, is important when you're writing code that is meant to stay at least a while (and very handy even if that is not the case). | ||
It is useful not only when you're working with someone else: if at some point you're lost in your code and don't understand why what was working perfectly few hours ago is now utterly broken it is really helpful to be able to compare what has changed since this last commit. | ||
The most obvious choice for a SCM is [git](https://git-scm.com) which is now widely abroad and has become the _de facto_ standard. _git_ is extremely versatile but you can already do a lot of version control with around 10 commands so the learning curve is not as steep as you may fear. | ||
git is generally already installed on your system or readily available through your package manager (or by installing XCode and its tools on macOS). | ||
There are many tutorials about how to use Git; including some from Inria: | ||
- [Support](https://gitlab.inria.fr/aabadie/formation-git) used in the training sessions by Alexandre Abadie (SED Paris). | ||
- A [nice tutorial](https://tutorial.gitlabpages.inria.fr/git/) from Mathias Malandain (SED Rennes) to learn to use Git and Gitlab at the same time. | ||
There are also fairly frequent training sessions organized in the Inria centers; ask your local SED if you're interested by one! | ||
%% Cell type:markdown id: tags: | ||
## Build system | ||
Handling properly the compilation of the code is not an easy task: many tutorial skip entirely the topic or just show a very basic example that is very far removed from a real project with potentially many third-party dependencies. This is understandable (and I will mostly do the same): using properly a build system is not trivial and may be the topic on a full lecture of its own. | ||
The usual possibilities are: | ||
* Build system provided by your IDE. Might be easier to use (definitely the case for XCode which I'm familiar with once you grasp how it is intended to work) but you bind your potential users to use the same IDE (even if now some relies upon CMake). | ||
* [Makefile](https://en.wikipedia.org/wiki/Makefile) is the venerable ancestor, which is really too painful to write and not automated enough for my taste. | ||
* [Ninja](https://ninja-build.org) is presented on this website as _a small build system with a focus on speed. It differs from other build systems in two major respects: it is designed to have its input files generated by a higher-level build system, and it is designed to run builds as fast as possible_. It is my favorite generator to use with CMake; meson also enables usage of Ninja under the hood. | ||
* [CMake](https://cmake.org) is the build system probably with the more traction now; it is a cross-platform build system which is rather powerful but not that easy to learn. Official documentation is terse; you may try [this](https://cliutils.gitlab.io/modern-cmake/) or [that](https://cgold.readthedocs.io/en/latest/) to understand it better. Please notice CMake was heavily changed when switching from version2 to version 3; take a recent documentation if you want to learn "modern" CMake. The principle of CMake is to provide a generic configuration that may be used for different build tools: by default you generate a Makefile, but you may choose another generator such as Ninja (see above) or a specific IDE. | ||
* [meson](https://mesonbuild.com/) is a more recent alternative which aims to be simpler to use than CMake. Never used it so can't say much about it. | ||
* [SCons](https://www.scons.org/) is a build system built upon Python which lets you write your own Python functions in the build system. The concept is appealing, but the actual use is actually dreadful and the provided build is much slower than what other build system provides. Avoid it! | ||
We will illustrate in next notebook a basic use of CMake. | ||
**Important:** Nowadays build systems can leverage the powerful computer on which they run and use several processors at the same time. Depending on the tool you use, the default build might be sequential or parallel (on the few I have used, only `ninja` assumes a parallel build by default). Make sure you know how your build tool works and that you're leveraging parallel builds! | ||
%% Cell type:markdown id: tags: | ||
[© Copyright](../COPYRIGHT.md) | ||
... | ... |
%% Cell type:markdown id: tags: | ||
# [Getting started in C++](./) - [C++ in a real environment](./0-main.ipynb) - [Set up environment](./1-SetUpEnvironment.ipynb) | ||
%% Cell type:markdown id: tags: | ||
## Introduction | ||
I will present here briefly how to set up a minimal development environment... only in Unix-like systems: sorry for Windows developers, but I have never set up a Windows environment for development. You may have a look at WSL, which is gaining traction and enables you to use Linux inside Windows. | ||
This will explain installation for two mainstreams compilers: [GNU compiler for C++](https://en.wikipedia.org/wiki/GNU_Compiler_Collection) and [clang++](https://en.wikipedia.org/wiki/Clang). | ||
## Installing a compiler | ||
**Note:** Compilers themselves will be addressed more in depth in an [upcoming notebook](3-Compilers.ipynb). | ||
### Ubuntu / Debian | ||
%% Cell type:markdown id: tags: | ||
#### Clang | ||
To install `clang` you need to specify explicitly the required version, e.g.: | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
// In a terminal | ||
sudo apt-get install -y clang++-13 | ||
``` | ||
%% Cell type:markdown id: tags: | ||
#### Default g++ | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
// In a terminal | ||
sudo apt-get install -y g++ | ||
``` | ||
%% Cell type:markdown id: tags: | ||
#### More recent gcc | ||
However, Ubuntu is rather conservative and the version you get might be a bit dated and it might be problematic if you intend to use the bleeding-edged features from the latest C++ standard (even if it's now better than what it used to be). | ||
In February 2024, default Ubuntu provided gcc 12; if you want gcc 13 you need to use the following [PPA](https://launchpad.net/ubuntu/+ppas): | ||
(_disclaimer_: the instructions below have been tested in a Docker image - with `RUN` instead of `sudo` of course - so all the lines might not be necessary in a full-fledged Ubuntu distro) | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
// In a terminal | ||
// Update the Ubuntu environment | ||
sudo apt-get update && sudo apt-get upgrade -y -q && sudo apt-get dist-upgrade -y -q && sudo apt-get -y -q autoclean && sudo apt-get -y -q autoremove) | ||
// To enable `add-apt-repository` command; probably not required in a full-fledged installation | ||
// but you will need it in a Docker image for instance | ||
sudo apt-get install --no-install-recommends -y software-properties-common gpg-agent wget | ||
// Adding PPA and making its content available to `apt`. | ||
sudo add-apt-repository ppa:ubuntu-toolchain-r/test | ||
sudo apt-get update -y | ||
// Installing the more recent gcc | ||
sudo apt-get install -y g++-13 | ||
``` | ||
%% Cell type:markdown id: tags: | ||
And to tell the system which version to use, the command is: | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
// In a terminal | ||
sudo update-alternatives --install /usr/bin/g++ g++ /usr/bin/g++-13 100 | ||
``` | ||
%% Cell type:markdown id: tags: | ||
More realistically, you will install gcc and perhaps gfortran as well; the following command make sure all are kept consistent (you do not want to mesh gcc 12 with g++ 13 for instance...): | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
// In a terminal | ||
sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-13 100 | ||
--slave /usr/bin/g++ g++ /usr/bin/g++-13 | ||
--slave /usr/bin/gfortran gfortran /usr/bin/gfortran-13 | ||
``` | ||
%% Cell type:markdown id: tags: | ||
### Fedora | ||
For development purposes I rather like Fedora, which provides more recent versions than Ubuntu and also a simple clang installation. | ||
%% Cell type:markdown id: tags: | ||
#### g++ | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
// In a terminal | ||
sudo dnf install -y gcc gcc-c++ gcc-gfortran | ||
``` | ||
%% Cell type:markdown id: tags: | ||
#### clang++ | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
// In a terminal | ||
sudo dnf install -y clang | ||
``` | ||
%% Cell type:markdown id: tags: | ||
### macOS | ||
* Install XCode from the AppStore | ||
* Install if requested the command line tools | ||
This will install _Apple Clang_ which is a customized version of `clang`. Unfortunately, Apple stopped providing the version of mainstream clang it is built upon; it's therefore more difficult to check if a new standard feature is already supported or not. | ||
It is also possible to install gcc on macOS; I personally use [Homebrew](https://brew.sh) to do so. However using it is not always reliable (on STL side at least - see below), especially shortly after a new version of XCode / Command Line Tools has been published; I would advise to use primarily clang. | ||
%% Cell type:markdown id: tags: | ||
## STL | ||
Besides the compiler, you may also choose which implementation of the STL you want to use. There are two mainstream choices: | ||
- `libstdc++`, which is the STL provided along gcc by GNU. This is the default choice for many Linux distro, and there is a good chance the binaries, libraries and share libraries in your package system were compiled with this one. | ||
- `libc++`, which is the STL provided along clang by LLVM. It is the default choice on macOS, and was until recently a pain to use with Ubuntu (according to Laurent it is much better now in Ubuntu 20.04 and more recent versions). | ||
Both are pretty solid choices: | ||
- Going with `libstdc++` is not a bad idea if you're using with your code libraries from your package manager that use this STL implementation (likely in a Linux distro). | ||
- Going with `libc++` along with clang++ seems rather natural as well. | ||
%% Cell type:markdown id: tags: | ||
Just a note for compatibility: `libc++` tends to provide more `include` directive in its header files than `libstdc++`. So don't be astonished if your code compiles well with `libc++` but complains about an unknown symbol from STL with `libstdc++` (and the patch is simply to use the missing include - a tool such as IncludeWhatYouUse would have underlined the missing include even when using `libc++`). | ||
%% Cell type:markdown id: tags: | ||
## Editor | ||
%% Cell type:markdown id: tags: | ||
You will need a [source code editor](https://en.wikipedia.org/wiki/Source_code_editor) to write your code; usually your system will provide a very basic one and you may be able to install another on your own. | ||
From my experience, there are essentially two types of developers: | ||
- Those that revel in using [VIM](https://en.wikipedia.org/wiki/Vim_(text_editor)) **or** [emacs](https://en.wikipedia.org/wiki/Emacs), which are lightweight editors that have been around for decades and are rather powerful once you've climbed a (very) steep learning curve. | ||
- Those that will like [integrated development environment](https://en.wikipedia.org/wiki/Integrated_development_environment) more, which provides more easily some facilities (that can often be configured the hard way in the aforementioned venerable text editors) but are more resource-intensive. | ||
I suggest you take whichever you're the most comfortable with and don't bother about the zealots that tell you their way is absolutely the best one. | ||
_Vim_ and _emacs_ are often either already installed or available easily with a distribution package (_apt_, _dnf_, etc...); for IDEs here are few of them: | ||
* [Visual Studio Code](https://code.visualstudio.com/), which gained traction in last few years and is one of the most sizeable GitHub project. This is an open-source and multi-platform editor maintained by Microsoft, not to be confused with [Visual Studio](https://visualstudio.microsoft.com/?rr=https%3A%2F%2Fwww.google.com%2F) - also provided by Microsoft on Windows (and with a fee). | ||
* [CLion](https://www.jetbrains.com/clion/) by JetBrains is also a rising star in IDEs; a free version is available for students (you may know PyCharm by the same company) | ||
* [Eclipse CDT](https://www.eclipse.org/cdt/) and [NetBeans](https://netbeans.org/) are other IDEs with more mileage. | ||
* [QtCreator](https://www.qt.io/qt-features-libraries-apis-tools-and-ide) is not just for Qt edition and might be used as a C++ IDE as well. | ||
* [XCode](https://developer.apple.com/xcode) is the editor provided by Apple on macOS. | ||
* [KDevelop](https://www.kdevelop.org/) is the IDE from the KDE project. | ||
* [JupyterLab](https://jupyter.org/) this very same notebook lab can be used as IDE after the last improvements and extensions added, [see this](https://towardsdatascience.com/jupyter-is-now-a-full-fledged-ide-c99218d33095) and how include the [VS Code Monaco Editor](https://imfing.medium.com/bring-vs-code-to-your-jupyterlab-187e59dd1c1b). I wouldn't advise it but if you're really keen to roll with it. | ||
%% Cell type:markdown id: tags: | ||
## Software configuration manager | ||
A [software configuration manager](https://en.wikipedia.org/wiki/Software_configuration_management), sometimes abbreviated as **SCM**, is important when you're writing code that is meant to stay at least a while (and very handy even if that is not the case). | ||
It is useful not only when you're working with someone else: if at some point you're lost in your code and don't understand why what was working perfectly few hours ago is now utterly broken it is really helpful to be able to compare what has changed since this last commit. | ||
The most obvious choice for a SCM is [git](https://git-scm.com) which is now widely abroad and has become the _de facto_ standard. _git_ is extremely versatile but you can already do a lot of version control with around 10 commands so the learning curve is not as steep as you may fear. | ||
git is generally already installed on your system or readily available through your package manager (or by installing XCode and its tools on macOS). | ||
There are many tutorials about how to use Git; including some from Inria: | ||
- [Support](https://gitlab.inria.fr/aabadie/formation-git) used in the training sessions by Alexandre Abadie (SED Paris). | ||
- A [nice tutorial](https://tutorial.gitlabpages.inria.fr/git/) from Mathias Malandain (SED Rennes) to learn to use Git and Gitlab at the same time. | ||
There are also fairly frequent training sessions organized in the Inria centers; ask your local SED if you're interested by one! | ||
%% Cell type:markdown id: tags: | ||
## Build system | ||
Handling properly the compilation of the code is not an easy task: many tutorial skip entirely the topic or just show a very basic example that is very far removed from a real project with potentially many third-party dependencies. This is understandable (and I will mostly do the same): using properly a build system is not trivial and may be the topic on a full lecture of its own. | ||
The usual possibilities are: | ||
* Build system provided by your IDE. Might be easier to use (definitely the case for XCode which I'm familiar with once you grasp how it is intended to work) but you bind your potential users to use the same IDE (even if now some relies upon CMake). | ||
* [Makefile](https://en.wikipedia.org/wiki/Makefile) is the venerable ancestor, which is really too painful to write and not automated enough for my taste. | ||
* [Ninja](https://ninja-build.org) is presented on this website as _a small build system with a focus on speed. It differs from other build systems in two major respects: it is designed to have its input files generated by a higher-level build system, and it is designed to run builds as fast as possible_. It is my favorite generator to use with CMake; meson also enables usage of Ninja under the hood. | ||
* [CMake](https://cmake.org) is the build system probably with the more traction now; it is a cross-platform build system which is rather powerful but not that easy to learn. Official documentation is terse; you may try [this](https://cliutils.gitlab.io/modern-cmake/) or [that](https://cgold.readthedocs.io/en/latest/) to understand it better. Please notice CMake was heavily changed when switching from version2 to version 3; take a recent documentation if you want to learn "modern" CMake. The principle of CMake is to provide a generic configuration that may be used for different build tools: by default you generate a Makefile, but you may choose another generator such as Ninja (see above) or a specific IDE. | ||
* [meson](https://mesonbuild.com/) is a more recent alternative which aims to be simpler to use than CMake. Never used it so can't say much about it. | ||
* [SCons](https://www.scons.org/) is a build system built upon Python which lets you write your own Python functions in the build system. The concept is appealing, but the actual use is actually dreadful and the provided build is much slower than what other build system provides. Avoid it! | ||
We will illustrate in next notebook a basic use of CMake. | ||
**Important:** Nowadays build systems can leverage the powerful computer on which they run and use several processors at the same time. Depending on the tool you use, the default build might be sequential or parallel (on the few I have used, only `ninja` assumes a parallel build by default). Make sure you know how your build tool works and that you're leveraging parallel builds! | ||
%% Cell type:markdown id: tags: | ||
[© Copyright](../COPYRIGHT.md) | ||
... | ... |
%% Cell type:markdown id: tags: | ||
# [Getting started in C++](./) - [C++ in a real environment](/notebooks/6-InRealEnvironment/0-main.ipynb) - [File structure in a C++ program](/notebooks/6-InRealEnvironment/2-FileStructure.ipynb) | ||
%% Cell type:markdown id: tags: | ||
## Library and program | ||
Contrary to for instance Python or Ruby, C++ is not a scripting language: it is intended to build either an **executable** or **library**. | ||
To summarize: | ||
* An **executable** runs the content of the [`main() function`](../1-ProceduralProgramming/4-Functions.ipynb#A-very-special-function:-main). There should be exactly one such function in all the compiled files; the file with this `main` must be compiled. | ||
* A **library** is a collection of functions, classes and so on that might be used in a program. A library may be **header-only**: in this case it is just an ensemble of header files with no file compiled. In this case all the definitions must be either **inline** or **template** (and possibly both of course). | ||
### Static and shared libraries | ||
A (non header) library may be constructed as one of the following type: | ||
* A **static** library, usually with a **.a** extension, is actually included directly into any executable that requires it. The advantage is that you just need the bare executable to run your code: the library is no longer required at runtime. The inconvenient is that the storage space may balloon up rather quickly: each executable will contain the whole library! | ||
* A **shared** library, which extension may vary wildly from one OS to another (**.dylib**, **.so**, **.dll**, etc...), is on the other hand required at runtime by the executable that was built with it. The advantage is that executables are thus much smaller. They are often described on the Web as the way to go; my personal experience with them is however less rosy as each OS handles them differently (noticeably the way to indicate in which location the dynamic libraries should be looked at differ rather wildly...) | ||
The best if possible is to enable generation of your library in either type... but it requires a bit of work with your build system. | ||
## Source file | ||
Contrary to most of more modern languages, C++ relies upon two very specific kind of files, each of which with their own extension schemes. We will introduce first the source file, with which basic programs might be achieved, and then show why header files are also needed. | ||
### Compilation of _Hello world!_ | ||
A source file is a type of file intended to be **compiled**. | ||
Let's consider the seminal _Hello world_ in a dedicated source file named _hello.cpp_ (all the examples here are made available in `2c-Demo` directory; this one is `01-HelloWorld`): | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
// File hello.cpp - I put "Code" as cell type in Jupyter to get nice colors but it's not intended | ||
// to be executed in the cell! | ||
#include <iostream> | ||
int main(int argc, char** argv) | ||
{ | ||
std::cout << "Hello world!" << std::endl; | ||
return EXIT_SUCCESS; | ||
} | ||
``` | ||
%% Cell type:markdown id: tags: | ||
To compile it on a Unix system, you will need to type in your terminal a line that looks like (with at least [GNU compiler for C++](https://en.wikipedia.org/wiki/GNU_Compiler_Collection) and [clang++](https://en.wikipedia.org/wiki/Clang)): | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
// In a terminal | ||
g++ -std=c++17 hello.cpp -o hello | ||
``` | ||
%% Cell type:markdown id: tags: | ||
where: | ||
- `g++` is the name of the compiler. You may provide `clang++` if you wish. | ||
- `-std=c++17` tells to use this version of the standard. If not specified the compilers tend to assume C++ 11 but may issue warnings if some features introduced with this standard are used. | ||
- `hello.cpp` is the name of the source file. | ||
- `hello` is the name of the executable produced. If the `-o hello` is omitted, the executable is arbitrarily named `a.out`, exactly as in C. | ||
%% Cell type:markdown id: tags: | ||
The executable may then be used with: | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
// In a terminal | ||
./hello | ||
``` | ||
%% Cell type:markdown id: tags: | ||
The `./` is there to specify the executable is to be looked at in current path; it may be omitted if `.` is present in the system `PATH` environment variable. | ||
Please notice the name of the file with the `main()` function and the name of the executable are completely custom; you have no requirement on the names of files and executable. | ||
%% Cell type:markdown id: tags: | ||
If your current machine has the compilers installed it is possible to execute these compilation commands instead of opening the terminal use the ! symbol as follows: | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
!g++ -std=c++17 ./2c-Demo/01-HelloWorld/hello.cpp -o hello | ||
``` | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
!./hello | ||
``` | ||
%% Cell type:markdown id: tags: | ||
### Source files extensions | ||
The plural is not a mistake: unfortunately, contrary to many languages, there is no universal convention upon the extensions to use for C++ files. There are widely spread conventions, but a library may choose not to follow them. | ||
Editors and IDE know the most common ones and usually provide a way to add your own spin so that they may provide language recognition and all that goes with it (colored syntax, completion helper and so on). | ||
The most common extensions are **.cpp**, **.cc**, **.C** and more seldom **.cxx**. | ||
My advice would be to choose one and stick to it; the only one I warn against is **.C** because some operating systems (such as macOS) are case-insensitive by default and **.c** is a more common convention for C programs. | ||
%% Cell type:markdown id: tags: | ||
### Expanding our hello program with two source files: one for main, one for the function | ||
This code is not very subtle: everything is in the same file, so we are in a very simplistic case in which only one file is compiled, and there are no need to find ways to specify how several files relate to each other. | ||
You may imagine working with a single file is not a very common option: it hinders reusability, and it would be cumbersome to navigate in a file with thousands or more lines of code (if you're curious about an extreme case, have a look at the amalgamation ([2.28 Mo zip here](https://www.sqlite.org/2020/sqlite-amalgamation-3310100.zip)) of sqlite code, in which all the code is put in a same source file...) | ||
We now want to separate the main() and the actual content of the code (also in `2c-Demo/02-InTwoFilesWithoutHeader`): | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
// File hello.cpp - no main inside | ||
#include <iostream> | ||
void hello() | ||
{ | ||
std::cout << "Hello world!" << std::endl; | ||
} | ||
``` | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
// File main.cpp | ||
#include <cstdlib> // for EXIT_SUCCESS | ||
int main(int argc, char** argv) | ||
{ | ||
hello(); | ||
return EXIT_SUCCESS; | ||
} | ||
``` | ||
%% Cell type:markdown id: tags: | ||
This brute force method is not working: a line on a terminal like: | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
// In a terminal | ||
clang++ -std=c++17 hello.cpp main.cpp -o hello | ||
``` | ||
%% Cell type:markdown id: tags: | ||
would yield something like: | ||
```verbatim | ||
main.cpp:5:5: error: use of undeclared identifier 'hello' | ||
hello(); | ||
^ | ||
1 error generated. | ||
``` | ||
%% Cell type:markdown id: tags: | ||
## Header file | ||
The issue above is that we need to inform the compiler when it attempts to compile `main.cpp` that `hello()` function is something that exists. We need to **declare** it in a dedicated **header file** and **include** this file in each source file that needs it (also in `2c-Demo/03-InTwoFilesWithHeader`): | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
// File hello.hpp | ||
void hello(); | ||
``` | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
// File main.cpp | ||
#include <cstdlib> // for EXIT_SUCCESS | ||
#include "hello.hpp" | ||
int main(int argc, char** argv) | ||
{ | ||
hello(); | ||
return EXIT_SUCCESS; | ||
} | ||
``` | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
// File hello.cpp - no main inside | ||
#include <iostream> | ||
#include "hello.hpp" | ||
void hello() | ||
{ | ||
std::cout << "Hello world!" << std::endl; | ||
} | ||
``` | ||
%% Cell type:markdown id: tags: | ||
With this few changes, the command line: | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
// In a terminal | ||
clang++ -std=c++17 hello.cpp main.cpp -o hello | ||
``` | ||
%% Cell type:markdown id: tags: | ||
works as expected and creates a valid `hello` executable (also note the header file is not required explicitly in this build command). | ||
As in the previous case we may directly compile from here using the ! symbol as follows (if compilers are present in the environment): | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
!g++ -std=c++17 2c-Demo/03-InTwoFilesWithHeader/hello.cpp 2c-Demo/03-InTwoFilesWithHeader/main.cpp -o hello | ||
``` | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
!./hello | ||
``` | ||
%% Cell type:markdown id: tags: | ||
### Header location | ||
You may have noticed that in the previous call to compile the executable the header file wasn't provided explicitly. | ||
`hello.hpp` was found because it was in the current folder. Let's suppose now we want to put include files in a directory named `incl`; to make it work we have actually two ways: | ||
* Either modifying the path in the source file. We would get | ||
```c++ | ||
#include "incl/hello.hpp" | ||
``` | ||
in both `hello.cpp` and `main.cpp`. | ||
* Or by giving to the command line the `-I` instruction to indicate which path to look for (`2c-Demo/04-SpecifyHeaderDirectory`): | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
// In a terminal | ||
clang++ -std=c++17 -Iincl hello.cpp main.cpp -o hello | ||
``` | ||
%% Cell type:markdown id: tags: | ||
As many `-I` as you wish may be provided on the command line; I would recommend not providing too many as it increases the risk of an ambiguity if two header files at different path are named likewise: | ||
```verbatim | ||
incl/foo.hpp | ||
bar/incl/foo.hpp | ||
``` | ||
and | ||
```shell | ||
clang++ -Iincl -Ibar/incl main.cpp | ||
``` | ||
leads to an ambiguity if there is `#include "foo.hpp"` in the `main.cpp`... | ||
%% Cell type:markdown id: tags: | ||
### `""` or `<>`? | ||
You may have noticed I sometimes used `<>` and sometimes `""` to specify the path for the include. | ||
The details don't matter that much in most cases, but it is better to: | ||
* Use `<>` only for the system libraries, typically STL or C headers should be this form. | ||
* Use `""` for your headers or for third-party libraries installed in specific locations. | ||
If you want a bit more details: | ||
* `""` will look first in the current directory, and then in the header files directories. | ||
* `<>` will look only in the header files directories. | ||
%% Cell type:markdown id: tags: | ||
### Header guards and #pragma once | ||
During compilation, the `#include` command is actually replaced by the content of the file which path is provided here. We therefore may quickly include twice the same content (`2c-Demo/05-NoHeaderGuards`): | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
// File foo.hpp | ||
class Foo | ||
{ }; | ||
``` | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
// File main.cpp | ||
#include <cstdlib> | ||
#include "foo.hpp" | ||
#include "foo.hpp" // Oops... | ||
int main() | ||
{ | ||
return EXIT_SUCCESS; | ||
} | ||
``` | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
// In terminal | ||
clang++ -std=c++17 main.cpp -o does_not_compile | ||
``` | ||
%% Cell type:markdown id: tags: | ||
doesn't compile: the translation unit provides two declarations of class Foo! | ||
This might seem a simple enough mistake to fix it, but in a project with few header files that might be intricated it becomes quickly too much a hassle (`2c-Demo/06-MoreSubtleNoHeaderGuards`): | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
// File foo.hpp | ||
class Foo | ||
{ }; | ||
``` | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
// File bar.hpp | ||
#include "foo.hpp" | ||
struct Bar | ||
{ | ||
Foo foo_; | ||
}; | ||
``` | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
// File main.cpp | ||
#include <cstdlib> | ||
#include "foo.hpp" | ||
#include "bar.hpp" // Compilation error: "foo.hpp" is sneakily included here as well! | ||
int main() | ||
{ | ||
Bar bar; | ||
return EXIT_SUCCESS; | ||
} | ||
``` | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
// In terminal | ||
clang++ -std=c++17 main.cpp -o does_not_compile | ||
``` | ||
%% Cell type:markdown id: tags: | ||
The patch is to indicate in each header file that it should be included **only once**. | ||
#### #pragma once | ||
There is the easy but non standard approach that is nonetheless [widely supported](https://en.wikipedia.org/wiki/Pragma_once#Portability) by compilers (`2c-Demo/07-PragmaOnce`): | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
// File foo.hpp | ||
#pragma once | ||
class Foo | ||
{ }; | ||
``` | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
// File bar.hpp | ||
#pragma once | ||
#include "foo.hpp" | ||
struct Bar | ||
{ | ||
Foo foo_; | ||
}; | ||
``` | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
// File main.cpp | ||
#include <cstdlib> | ||
#include "foo.hpp" | ||
#include "bar.hpp" | ||
int main() | ||
{ | ||
return EXIT_SUCCESS; | ||
} | ||
``` | ||
%% Cell type:markdown id: tags: | ||
This prevents the inclusion of `foo.hpp` twice; and now `clang++ -std=c++17 main.cpp -o do_nothing` compiles correctly. | ||
%% Cell type:markdown id: tags: | ||
#### Header guards | ||
The "official" way to protect files - the use of so-called **header guards** - fully supported by the standard, is much more clunky (`2c-Demo/08-HeaderGuards`): | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
// File foo.hpp | ||
#ifndef FOO_HPP // If this macro is not yet defined, proceed to the rest of the file. | ||
#define FOO_HPP // Immediately define it so next call won't include again the file content. | ||
class Foo | ||
{ }; | ||
#endif // FOO_HPP // End of the macro block that begun with #ifndef | ||
``` | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
// File bar.hpp | ||
#ifndef BAR_HPP // If this macro is not yet defined, proceed to the rest of the file. | ||
#define BAR_HPP // Immediately define it so next call won't include again the file content. | ||
#include "foo.hpp" | ||
struct Bar | ||
{ | ||
Foo foo_; | ||
}; | ||
#endif // BAR_HPP // End of the macro block that begun with #ifndef | ||
``` | ||
%% Cell type:markdown id: tags: | ||
You may check that `clang++ -std=c++17 main.cpp -o do_nothing` compiles properly as well. | ||
%% Cell type:markdown id: tags: | ||
##### **[WARNING]** Ensure unicity of header guards | ||
There is however a catch with header guards: you must ensure that the macro for a given file is used only once. Let's consider the previous case, but with a bug (`2c-Demo/09-HeaderGuardsBug`): | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
// File foo.hpp | ||
#ifndef FOO_HPP // If this macro is not yet defined, proceed to the rest of the file. | ||
#define FOO_HPP // Immediately define it so next call won't include again the file content. | ||
class Foo | ||
{ }; | ||
#endif // FOO_HPP // End of the macro block that begun with #ifndef | ||
``` | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
// File bar.hpp | ||
#ifndef FOO_HPP // bug here! | ||
#define FOO_HPP | ||
#include "foo.hpp" | ||
struct Bar | ||
{ | ||
Foo foo_; | ||
}; | ||
#endif // FOO_HPP | ||
``` | ||
%% Cell type:markdown id: tags: | ||
`clang++ -std=c++17 main.cpp` does not compile, with the terse message: | ||
```shell | ||
main.cpp:7:5: error: unknown type name 'Bar' | ||
Bar bar; | ||
``` | ||
%% Cell type:markdown id: tags: | ||
And in a more developed code, it might be a nightmare to identify this kind of bug... | ||
A common strategy is to define a header guard name based on the location of the source file in the tree; this circumvent the case in which two files share a same name (quite common in a large codebase...) | ||
One of us (Sébastien) uses up a [Python script](https://gitlab.inria.fr/MoReFEM/CoreLibrary/MoReFEM/raw/master/Scripts/header_guards.py) which iterates through all the C++ files in his library, identify the header guards of each header file and check they are a mix of the project name and the path of the file. This is definitely much more clunky than **#pragma once** ! | ||
But as we said the latter is non standard and there are hot discussions about whether it is safe or not for all set-ups (at some point it was complicated to use if there were symbolic or hard links in the project). | ||
%% Cell type:markdown id: tags: | ||
### Header files extensions | ||
The most current header files extensions are **.hpp**, **.h**, **.hh** and more seldom **.hxx**. I definitely do not recommend **.h**: this is also the extension used for C header files, and some compiler even issue a warning if you're using it in a C++ context. | ||
#### My personal convention (Sébastien) | ||
Personally I am using both **.hpp** and **.hxx**: | ||
* **.hpp** is for the declaration of functions, classes, and so on. | ||
* **.hxx** is for the definitions of inline functions and templates. | ||
The **.hxx** is included at the end of **.hpp** file; this way: | ||
* End-user just includes the **.hpp** files in his code; he **never** needs to bother about including **.hxx** or not. | ||
* The **hpp** file is not too long and includes only declarations with additionally Doxygen comments to explain the API. | ||
And you may have noticed that standard library headers get no extension at all! | ||
%% Cell type:markdown id: tags: | ||
## Why a build system: very basic CMake demonstration | ||
Let's take back our mighty "Hello world" example with a slight extension: we want to query the identity of the user and print that instead. We will foolishly add this new function in yet another file for the sake of illustration only (`2c-Demo/10-CMake`): | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
// File hello.hpp | ||
#ifndef HELLO_HPP | ||
#define HELLO_HPP | ||
void Hello(); | ||
#endif // HELLO_HPP | ||
``` | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
// File who-are-you.hpp | ||
#ifndef WHO_ARE_YOU_H | ||
#define WHO_ARE_YOU_H | ||
#include <string> | ||
std::string WhoAreYou(); | ||
#endif // WHO_ARE_YOU_H | ||
``` | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
// File hello.cpp | ||
#include <iostream> | ||
#include "hello.hpp" | ||
#include "who-are-you.hpp" | ||
void hello() | ||
{ | ||
auto identity = WhoAreYou(); | ||
std::cout << "Hello " << identity << '!' << std::endl; | ||
} | ||
``` | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
// File who-are-you.cpp | ||
#include <iostream> | ||
#include "who-are-you.hpp" | ||
std::string WhoAreYou() | ||
{ | ||
std::string name; | ||
std::cout << "What's your name? "; | ||
std::cin >> name; // not much safety here but this is not the current point! | ||
return name; | ||
} | ||
``` | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
// File main.cpp | ||
#include <cstdlib> // For EXIT_SUCCESS | ||
#include "hello.hpp" | ||
int main(int argc, char** argv) | ||
{ | ||
Hello(); | ||
return EXIT_SUCCESS; | ||
} | ||
``` | ||
%% Cell type:markdown id: tags: | ||
Up to now, we compiled such a program with manually: | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
// In terminal | ||
clang++ -std=c++17 -c hello.cpp | ||
clang++ -std=c++17 -c main.cpp | ||
clang++ -std=c++17 -c who-are-you.cpp | ||
clang++ -std=c++17 *.o -o hello | ||
``` | ||
%% Cell type:markdown id: tags: | ||
The issue with that is that it's not robust at all: either you recompile everything all the time (and let's face it: it's tedious even with our limited number of files...) or you have to keep track of which should be recompiled. For instance if `who-are-you.hpp` is modified all source files include it and must be recompiled, but if it is `hello.hpp` `who_are_you.cpp` is not modified. | ||
It is to handle automatically this and limit the compilation to only what is required that build systems (which we talked about briefly [here](./1-SetUpEnvironment.ipynb#Build-system)) were introduced. Let's see a brief CMake configuration file named by convention `CMakeLists.txt`: | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
# CMakeLists.txt | ||
# Ensure the cmake used is compatible with the CMake functions that are used | ||
cmake_minimum_required(VERSION 3.20) | ||
# A project name is mandatory, preferably right after cmake_minimum_required call | ||
project(Hello) | ||
set(CMAKE_CXX_STANDARD 17 CACHE STRING "C++ standard; at least 17 is expected.") | ||
add_executable(hello | ||
main.cpp | ||
hello.cpp | ||
who-are-you.cpp) | ||
``` | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
// In terminal | ||
mkdir build // create a directory to separate build from source files and so on | ||
cd build | ||
cmake .. // will create the Makefile; as no generator was provided with -G Unix makefile is chosen. | ||
// The directory indicated by .. MUST include the main CMakeLists.txt of the project. | ||
make | ||
``` | ||
%% Cell type:markdown id: tags: | ||
This command creates the executable in current directory; now if we modified one file the build system will rebuild all that needs it and nothing more. | ||
%% Cell type:markdown id: tags: | ||
If `main.cpp` and `hello.cpp` may also be used jointly for another executable, they may be put together in a library; replace the former `add_executable` command by: | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
add_library(hello_lib | ||
SHARED | ||
hello.cpp | ||
who-are-you.cpp) | ||
add_executable(hello | ||
main.cpp) | ||
target_link_libraries(hello | ||
hello_lib) | ||
``` | ||
%% Cell type:markdown id: tags: | ||
SHARED may be replaced by STATIC to use a static library instead. | ||
%% Cell type:markdown id: tags: | ||
You can run these commands directly with the ! symbol as follows: | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
!cd ./2c-Demo/7-CMake/ && mkdir build && cd build && cmake .. && make | ||
``` | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
!cd ./2c-Demo/7-CMake/build && ./hello | ||
``` | ||
%% Cell type:markdown id: tags: | ||
## Where should the headers be included? | ||
* Each time a header is modified, all the source files that include it directly or indirectly are recompiled. | ||
* Each time a source file is modified, only this source file is modified; some relinking for the libraries and executables that depend on it will also occur (linking is the step that glue together the object files and libraries; the term _compilation_ is often - included in this very tutorial - abusively used to encompass both compilation and link phases). | ||
Thus it might seem a good idea to put as much as possible `#include` directives in the source files **rather than in include files**... hence limiting the compilation time. This is a generally very good advice... provided we do not err on the wrong side and put enough in the header file: | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
// File foo.hpp | ||
#ifndef FOO_HPP | ||
# define FOO_HPP | ||
#include <string> | ||
void Print(std::string text); | ||
#endif // FOO_HPP | ||
``` | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
// File foo.cpp | ||
#include <iostream> | ||
#include "foo.hpp" | ||
void Print(std::string text) | ||
{ | ||
std::cout << "The text to be printed is: \"" << text << "\"." << std::endl; | ||
} | ||
``` | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
// File main.cpp | ||
#include <cstdlib> | ||
#include "foo.hpp" | ||
int main() | ||
{ | ||
Print("Hello world!"); | ||
return EXIT_SUCCESS; | ||
} | ||
``` | ||
%% Cell type:markdown id: tags: | ||
You may have noticed `string` and `iostream` are not dealt with the same way... and rightly so: | ||
* `#include <iostream>` is only in the source file: it is actually needed only for `std::cout` and `std::endl`, which are implementation details of `Print()` function: neither appears in the signature of the function. | ||
* `#include <string>` is present in `foo.hpp` as it is required to give the information about the type of the prototype to be used. If you do not do that, each time you include `foo.hpp` you would need to include as well `string`; doing so leads to unmaintainable code as you would have to track down all the includes that are required with each include... | ||
So to put in a nutshell: | ||
* Put in the header files all the includes that are mandatory to make the prototypes understandable. A rule of thumb is that a source file that would only include the header file should be compilable: | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
// File foo.hpp | ||
std::string Print(); | ||
``` | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
// File check_foo.cpp | ||
#include <cstdlib> | ||
#include "foo.hpp" | ||
int main(int, char**) | ||
{ | ||
return EXIT_SUCCESS; | ||
} // DOES NOT COMPILE => header is ill-formed! | ||
``` | ||
%% Cell type:markdown id: tags: | ||
* Include that are here for implementation details should on the other hand be preferably in source files. Of course, you may not be able to do that in any case: for instance templates are by construction defined in header files! | ||
%% Cell type:markdown id: tags: | ||
Some tools such as [include-what-you-use](https://include-what-you-use.org/) are rather helpful to help cut off the unrequired includes in file, but they need a bit of time to configure and set up properly, especially on an already large codebase. | ||
%% Cell type:markdown id: tags: | ||
## Forward declaration | ||
There is actually an exception to the first rule I've just given: **forward declaration**. This is really a trick that may be used to reduce compilation time, with some caveats. | ||
The idea is that if a type intervenes in a header file **only as a reference and/or as a (smart) pointer**, it might be forward-declared: its type is merely given in the header (`2c-Demo/11-Forward`) | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
// File foo.hpp | ||
#ifndef FOO_HPP | ||
# define FOO_HPP | ||
// Forward declaration: we say a class Bar is meant to exist... | ||
class Bar; | ||
struct Foo | ||
{ | ||
Foo(int n); | ||
void Print() const; | ||
Bar* bar_ = nullptr; | ||
}; | ||
#endif // FOO_HPP | ||
``` | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
// File check_header_ok.cpp | ||
#include <cstdlib> | ||
#include "foo.hpp" | ||
int main(int, char**) | ||
{ | ||
return EXIT_SUCCESS; | ||
} | ||
``` | ||
%% Cell type:markdown id: tags: | ||
and `clang++ -std=c++17 check_header_ok.cpp` compiles properly (you may try commenting out the forward declaration line to check it does not without it) | ||
This is not without cost: obviously in a file where `Bar` is actually needed you will need to include it properly: with just `#include "foo.hpp"` you can't for instance call a method of `Bar` class. | ||
Typically the `include "bar.hpp"` will be located in the `foo.cpp` file, in which you will probably need the `Bar` object interface to define your `Foo` object (or if not you may question why you chose to put the `bar_` data attribute in the first place) | ||
It is nonetheless a very nice trick to know; there is even an idiom call [Pimpl idiom](https://arne-mertz.de/2019/01/the-pimpl-idiom/) that relies upon forward declaration. | ||
This is however not the only use for it though: to define a shared_ptr/weak_ptr you [also need](../7-Appendix/WeakPtr.ipynb) to use this capability. | ||
The tool [include-what-you-use](https://include-what-you-use.org/) mentioned earlier is able to suggest as well what should be forward-declared. | ||
%% Cell type:markdown id: tags: | ||
[© Copyright](../COPYRIGHT.md) | ||
... | ... |
%% Cell type:markdown id: tags: | ||
# [Getting started in C++](./) - [C++ in a real environment](/notebooks/6-InRealEnvironment/0-main.ipynb) - [File structure in a C++ program](/notebooks/6-InRealEnvironment/2-FileStructure.ipynb) | ||
%% Cell type:markdown id: tags: | ||
## Library and program | ||
Contrary to for instance Python or Ruby, C++ is not a scripting language: it is intended to build either an **executable** or **library**. | ||
To summarize: | ||
* An **executable** runs the content of the [`main() function`](../1-ProceduralProgramming/4-Functions.ipynb#A-very-special-function:-main). There should be exactly one such function in all the compiled files; the file with this `main` must be compiled. | ||
* A **library** is a collection of functions, classes and so on that might be used in a program. A library may be **header-only**: in this case it is just an ensemble of header files with no file compiled. In this case all the definitions must be either **inline** or **template** (and possibly both of course). | ||
### Static and shared libraries | ||
A (non header) library may be constructed as one of the following type: | ||
* A **static** library, usually with a **.a** extension, is actually included directly into any executable that requires it. The advantage is that you just need the bare executable to run your code: the library is no longer required at runtime. The inconvenient is that the storage space may balloon up rather quickly: each executable will contain the whole library! | ||
* A **shared** library, which extension may vary wildly from one OS to another (**.dylib**, **.so**, **.dll**, etc...), is on the other hand required at runtime by the executable that was built with it. The advantage is that executables are thus much smaller. They are often described on the Web as the way to go; my personal experience with them is however less rosy as each OS handles them differently (noticeably the way to indicate in which location the dynamic libraries should be looked at differ rather wildly...) | ||
The best if possible is to enable generation of your library in either type... but it requires a bit of work with your build system. | ||
## Source file | ||
Contrary to most of more modern languages, C++ relies upon two very specific kind of files, each of which with their own extension schemes. We will introduce first the source file, with which basic programs might be achieved, and then show why header files are also needed. | ||
### Compilation of _Hello world!_ | ||
A source file is a type of file intended to be **compiled**. | ||
Let's consider the seminal _Hello world_ in a dedicated source file named _hello.cpp_ (all the examples here are made available in `2c-Demo` directory; this one is `01-HelloWorld`): | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
// File hello.cpp - I put "Code" as cell type in Jupyter to get nice colors but it's not intended | ||
// to be executed in the cell! | ||
#include <iostream> | ||
int main(int argc, char** argv) | ||
{ | ||
std::cout << "Hello world!" << std::endl; | ||
return EXIT_SUCCESS; | ||
} | ||
``` | ||
%% Cell type:markdown id: tags: | ||
To compile it on a Unix system, you will need to type in your terminal a line that looks like (with at least [GNU compiler for C++](https://en.wikipedia.org/wiki/GNU_Compiler_Collection) and [clang++](https://en.wikipedia.org/wiki/Clang)): | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
// In a terminal | ||
g++ -std=c++17 hello.cpp -o hello | ||
``` | ||
%% Cell type:markdown id: tags: | ||
where: | ||
- `g++` is the name of the compiler. You may provide `clang++` if you wish. | ||
- `-std=c++17` tells to use this version of the standard. If not specified the compilers tend to assume C++ 11 but may issue warnings if some features introduced with this standard are used. | ||
- `hello.cpp` is the name of the source file. | ||
- `hello` is the name of the executable produced. If the `-o hello` is omitted, the executable is arbitrarily named `a.out`, exactly as in C. | ||
%% Cell type:markdown id: tags: | ||
The executable may then be used with: | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
// In a terminal | ||
./hello | ||
``` | ||
%% Cell type:markdown id: tags: | ||
The `./` is there to specify the executable is to be looked at in current path; it may be omitted if `.` is present in the system `PATH` environment variable. | ||
Please notice the name of the file with the `main()` function and the name of the executable are completely custom; you have no requirement on the names of files and executable. | ||
%% Cell type:markdown id: tags: | ||
If your current machine has the compilers installed it is possible to execute these compilation commands instead of opening the terminal use the ! symbol as follows: | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
!g++ -std=c++17 ./2c-Demo/01-HelloWorld/hello.cpp -o hello | ||
``` | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
!./hello | ||
``` | ||
%% Cell type:markdown id: tags: | ||
### Source files extensions | ||
The plural is not a mistake: unfortunately, contrary to many languages, there is no universal convention upon the extensions to use for C++ files. There are widely spread conventions, but a library may choose not to follow them. | ||
Editors and IDE know the most common ones and usually provide a way to add your own spin so that they may provide language recognition and all that goes with it (colored syntax, completion helper and so on). | ||
The most common extensions are **.cpp**, **.cc**, **.C** and more seldom **.cxx**. | ||
My advice would be to choose one and stick to it; the only one I warn against is **.C** because some operating systems (such as macOS) are case-insensitive by default and **.c** is a more common convention for C programs. | ||
%% Cell type:markdown id: tags: | ||
### Expanding our hello program with two source files: one for main, one for the function | ||
This code is not very subtle: everything is in the same file, so we are in a very simplistic case in which only one file is compiled, and there are no need to find ways to specify how several files relate to each other. | ||
You may imagine working with a single file is not a very common option: it hinders reusability, and it would be cumbersome to navigate in a file with thousands or more lines of code (if you're curious about an extreme case, have a look at the amalgamation ([2.28 Mo zip here](https://www.sqlite.org/2020/sqlite-amalgamation-3310100.zip)) of sqlite code, in which all the code is put in a same source file...) | ||
We now want to separate the main() and the actual content of the code (also in `2c-Demo/02-InTwoFilesWithoutHeader`): | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
// File hello.cpp - no main inside | ||
#include <iostream> | ||
void hello() | ||
{ | ||
std::cout << "Hello world!" << std::endl; | ||
} | ||
``` | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
// File main.cpp | ||
#include <cstdlib> // for EXIT_SUCCESS | ||
int main(int argc, char** argv) | ||
{ | ||
hello(); | ||
return EXIT_SUCCESS; | ||
} | ||
``` | ||
%% Cell type:markdown id: tags: | ||
This brute force method is not working: a line on a terminal like: | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
// In a terminal | ||
clang++ -std=c++17 hello.cpp main.cpp -o hello | ||
``` | ||
%% Cell type:markdown id: tags: | ||
would yield something like: | ||
```verbatim | ||
main.cpp:5:5: error: use of undeclared identifier 'hello' | ||
hello(); | ||
^ | ||
1 error generated. | ||
``` | ||
%% Cell type:markdown id: tags: | ||
## Header file | ||
The issue above is that we need to inform the compiler when it attempts to compile `main.cpp` that `hello()` function is something that exists. We need to **declare** it in a dedicated **header file** and **include** this file in each source file that needs it (also in `2c-Demo/03-InTwoFilesWithHeader`): | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
// File hello.hpp | ||
void hello(); | ||
``` | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
// File main.cpp | ||
#include <cstdlib> // for EXIT_SUCCESS | ||
#include "hello.hpp" | ||
int main(int argc, char** argv) | ||
{ | ||
hello(); | ||
return EXIT_SUCCESS; | ||
} | ||
``` | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
// File hello.cpp - no main inside | ||
#include <iostream> | ||
#include "hello.hpp" | ||
void hello() | ||
{ | ||
std::cout << "Hello world!" << std::endl; | ||
} | ||
``` | ||
%% Cell type:markdown id: tags: | ||
With this few changes, the command line: | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
// In a terminal | ||
clang++ -std=c++17 hello.cpp main.cpp -o hello | ||
``` | ||
%% Cell type:markdown id: tags: | ||
works as expected and creates a valid `hello` executable (also note the header file is not required explicitly in this build command). | ||
As in the previous case we may directly compile from here using the ! symbol as follows (if compilers are present in the environment): | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
!g++ -std=c++17 2c-Demo/03-InTwoFilesWithHeader/hello.cpp 2c-Demo/03-InTwoFilesWithHeader/main.cpp -o hello | ||
``` | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
!./hello | ||
``` | ||
%% Cell type:markdown id: tags: | ||
### Header location | ||
You may have noticed that in the previous call to compile the executable the header file wasn't provided explicitly. | ||
`hello.hpp` was found because it was in the current folder. Let's suppose now we want to put include files in a directory named `incl`; to make it work we have actually two ways: | ||
* Either modifying the path in the source file. We would get | ||
```c++ | ||
#include "incl/hello.hpp" | ||
``` | ||
in both `hello.cpp` and `main.cpp`. | ||
* Or by giving to the command line the `-I` instruction to indicate which path to look for (`2c-Demo/04-SpecifyHeaderDirectory`): | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
// In a terminal | ||
clang++ -std=c++17 -Iincl hello.cpp main.cpp -o hello | ||
``` | ||
%% Cell type:markdown id: tags: | ||
As many `-I` as you wish may be provided on the command line; I would recommend not providing too many as it increases the risk of an ambiguity if two header files at different path are named likewise: | ||
```verbatim | ||
incl/foo.hpp | ||
bar/incl/foo.hpp | ||
``` | ||
and | ||
```shell | ||
clang++ -Iincl -Ibar/incl main.cpp | ||
``` | ||
leads to an ambiguity if there is `#include "foo.hpp"` in the `main.cpp`... | ||
%% Cell type:markdown id: tags: | ||
### `""` or `<>`? | ||
You may have noticed I sometimes used `<>` and sometimes `""` to specify the path for the include. | ||
The details don't matter that much in most cases, but it is better to: | ||
* Use `<>` only for the system libraries, typically STL or C headers should be this form. | ||
* Use `""` for your headers or for third-party libraries installed in specific locations. | ||
If you want a bit more details: | ||
* `""` will look first in the current directory, and then in the header files directories. | ||
* `<>` will look only in the header files directories. | ||
%% Cell type:markdown id: tags: | ||
### Header guards and #pragma once | ||
During compilation, the `#include` command is actually replaced by the content of the file which path is provided here. We therefore may quickly include twice the same content (`2c-Demo/05-NoHeaderGuards`): | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
// File foo.hpp | ||
class Foo | ||
{ }; | ||
``` | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
// File main.cpp | ||
#include <cstdlib> | ||
#include "foo.hpp" | ||
#include "foo.hpp" // Oops... | ||
int main() | ||
{ | ||
return EXIT_SUCCESS; | ||
} | ||
``` | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
// In terminal | ||
clang++ -std=c++17 main.cpp -o does_not_compile | ||
``` | ||
%% Cell type:markdown id: tags: | ||
doesn't compile: the translation unit provides two declarations of class Foo! | ||
This might seem a simple enough mistake to fix it, but in a project with few header files that might be intricated it becomes quickly too much a hassle (`2c-Demo/06-MoreSubtleNoHeaderGuards`): | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
// File foo.hpp | ||
class Foo | ||
{ }; | ||
``` | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
// File bar.hpp | ||
#include "foo.hpp" | ||
struct Bar | ||
{ | ||
Foo foo_; | ||
}; | ||
``` | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
// File main.cpp | ||
#include <cstdlib> | ||
#include "foo.hpp" | ||
#include "bar.hpp" // Compilation error: "foo.hpp" is sneakily included here as well! | ||
int main() | ||
{ | ||
Bar bar; | ||
return EXIT_SUCCESS; | ||
} | ||
``` | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
// In terminal | ||
clang++ -std=c++17 main.cpp -o does_not_compile | ||
``` | ||
%% Cell type:markdown id: tags: | ||
The patch is to indicate in each header file that it should be included **only once**. | ||
#### #pragma once | ||
There is the easy but non standard approach that is nonetheless [widely supported](https://en.wikipedia.org/wiki/Pragma_once#Portability) by compilers (`2c-Demo/07-PragmaOnce`): | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
// File foo.hpp | ||
#pragma once | ||
class Foo | ||
{ }; | ||
``` | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
// File bar.hpp | ||
#pragma once | ||
#include "foo.hpp" | ||
struct Bar | ||
{ | ||
Foo foo_; | ||
}; | ||
``` | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
// File main.cpp | ||
#include <cstdlib> | ||
#include "foo.hpp" | ||
#include "bar.hpp" | ||
int main() | ||
{ | ||
return EXIT_SUCCESS; | ||
} | ||
``` | ||
%% Cell type:markdown id: tags: | ||
This prevents the inclusion of `foo.hpp` twice; and now `clang++ -std=c++17 main.cpp -o do_nothing` compiles correctly. | ||
%% Cell type:markdown id: tags: | ||
#### Header guards | ||
The "official" way to protect files - the use of so-called **header guards** - fully supported by the standard, is much more clunky (`2c-Demo/08-HeaderGuards`): | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
// File foo.hpp | ||
#ifndef FOO_HPP // If this macro is not yet defined, proceed to the rest of the file. | ||
#define FOO_HPP // Immediately define it so next call won't include again the file content. | ||
class Foo | ||
{ }; | ||
#endif // FOO_HPP // End of the macro block that begun with #ifndef | ||
``` | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
// File bar.hpp | ||
#ifndef BAR_HPP // If this macro is not yet defined, proceed to the rest of the file. | ||
#define BAR_HPP // Immediately define it so next call won't include again the file content. | ||
#include "foo.hpp" | ||
struct Bar | ||
{ | ||
Foo foo_; | ||
}; | ||
#endif // BAR_HPP // End of the macro block that begun with #ifndef | ||
``` | ||
%% Cell type:markdown id: tags: | ||
You may check that `clang++ -std=c++17 main.cpp -o do_nothing` compiles properly as well. | ||
%% Cell type:markdown id: tags: | ||
##### **[WARNING]** Ensure unicity of header guards | ||
There is however a catch with header guards: you must ensure that the macro for a given file is used only once. Let's consider the previous case, but with a bug (`2c-Demo/09-HeaderGuardsBug`): | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
// File foo.hpp | ||
#ifndef FOO_HPP // If this macro is not yet defined, proceed to the rest of the file. | ||
#define FOO_HPP // Immediately define it so next call won't include again the file content. | ||
class Foo | ||
{ }; | ||
#endif // FOO_HPP // End of the macro block that begun with #ifndef | ||
``` | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
// File bar.hpp | ||
#ifndef FOO_HPP // bug here! | ||
#define FOO_HPP | ||
#include "foo.hpp" | ||
struct Bar | ||
{ | ||
Foo foo_; | ||
}; | ||
#endif // FOO_HPP | ||
``` | ||
%% Cell type:markdown id: tags: | ||
`clang++ -std=c++17 main.cpp` does not compile, with the terse message: | ||
```shell | ||
main.cpp:7:5: error: unknown type name 'Bar' | ||
Bar bar; | ||
``` | ||
%% Cell type:markdown id: tags: | ||
And in a more developed code, it might be a nightmare to identify this kind of bug... | ||
A common strategy is to define a header guard name based on the location of the source file in the tree; this circumvent the case in which two files share a same name (quite common in a large codebase...) | ||
One of us (Sébastien) uses up a [Python script](https://gitlab.inria.fr/MoReFEM/CoreLibrary/MoReFEM/raw/master/Scripts/header_guards.py) which iterates through all the C++ files in his library, identify the header guards of each header file and check they are a mix of the project name and the path of the file. This is definitely much more clunky than **#pragma once** ! | ||
But as we said the latter is non standard and there are hot discussions about whether it is safe or not for all set-ups (at some point it was complicated to use if there were symbolic or hard links in the project). | ||
%% Cell type:markdown id: tags: | ||
### Header files extensions | ||
The most current header files extensions are **.hpp**, **.h**, **.hh** and more seldom **.hxx**. I definitely do not recommend **.h**: this is also the extension used for C header files, and some compiler even issue a warning if you're using it in a C++ context. | ||
#### My personal convention (Sébastien) | ||
Personally I am using both **.hpp** and **.hxx**: | ||
* **.hpp** is for the declaration of functions, classes, and so on. | ||
* **.hxx** is for the definitions of inline functions and templates. | ||
The **.hxx** is included at the end of **.hpp** file; this way: | ||
* End-user just includes the **.hpp** files in his code; he **never** needs to bother about including **.hxx** or not. | ||
* The **hpp** file is not too long and includes only declarations with additionally Doxygen comments to explain the API. | ||
And you may have noticed that standard library headers get no extension at all! | ||
%% Cell type:markdown id: tags: | ||
## Why a build system: very basic CMake demonstration | ||
Let's take back our mighty "Hello world" example with a slight extension: we want to query the identity of the user and print that instead. We will foolishly add this new function in yet another file for the sake of illustration only (`2c-Demo/10-CMake`): | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
// File hello.hpp | ||
#ifndef HELLO_HPP | ||
#define HELLO_HPP | ||
void Hello(); | ||
#endif // HELLO_HPP | ||
``` | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
// File who-are-you.hpp | ||
#ifndef WHO_ARE_YOU_H | ||
#define WHO_ARE_YOU_H | ||
#include <string> | ||
std::string WhoAreYou(); | ||
#endif // WHO_ARE_YOU_H | ||
``` | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
// File hello.cpp | ||
#include <iostream> | ||
#include "hello.hpp" | ||
#include "who-are-you.hpp" | ||
void hello() | ||
{ | ||
auto identity = WhoAreYou(); | ||
std::cout << "Hello " << identity << '!' << std::endl; | ||
} | ||
``` | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
// File who-are-you.cpp | ||
#include <iostream> | ||
#include "who-are-you.hpp" | ||
std::string WhoAreYou() | ||
{ | ||
std::string name; | ||
std::cout << "What's your name? "; | ||
std::cin >> name; // not much safety here but this is not the current point! | ||
return name; | ||
} | ||
``` | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
// File main.cpp | ||
#include <cstdlib> // For EXIT_SUCCESS | ||
#include "hello.hpp" | ||
int main(int argc, char** argv) | ||
{ | ||
Hello(); | ||
return EXIT_SUCCESS; | ||
} | ||
``` | ||
%% Cell type:markdown id: tags: | ||
Up to now, we compiled such a program with manually: | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
// In terminal | ||
clang++ -std=c++17 -c hello.cpp | ||
clang++ -std=c++17 -c main.cpp | ||
clang++ -std=c++17 -c who-are-you.cpp | ||
clang++ -std=c++17 *.o -o hello | ||
``` | ||
%% Cell type:markdown id: tags: | ||
The issue with that is that it's not robust at all: either you recompile everything all the time (and let's face it: it's tedious even with our limited number of files...) or you have to keep track of which should be recompiled. For instance if `who-are-you.hpp` is modified all source files include it and must be recompiled, but if it is `hello.hpp` `who_are_you.cpp` is not modified. | ||
It is to handle automatically this and limit the compilation to only what is required that build systems (which we talked about briefly [here](./1-SetUpEnvironment.ipynb#Build-system)) were introduced. Let's see a brief CMake configuration file named by convention `CMakeLists.txt`: | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
# CMakeLists.txt | ||
# Ensure the cmake used is compatible with the CMake functions that are used | ||
cmake_minimum_required(VERSION 3.20) | ||
# A project name is mandatory, preferably right after cmake_minimum_required call | ||
project(Hello) | ||
set(CMAKE_CXX_STANDARD 17 CACHE STRING "C++ standard; at least 17 is expected.") | ||
add_executable(hello | ||
main.cpp | ||
hello.cpp | ||
who-are-you.cpp) | ||
``` | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
// In terminal | ||
mkdir build // create a directory to separate build from source files and so on | ||
cd build | ||
cmake .. // will create the Makefile; as no generator was provided with -G Unix makefile is chosen. | ||
// The directory indicated by .. MUST include the main CMakeLists.txt of the project. | ||
make | ||
``` | ||
%% Cell type:markdown id: tags: | ||
This command creates the executable in current directory; now if we modified one file the build system will rebuild all that needs it and nothing more. | ||
%% Cell type:markdown id: tags: | ||
If `main.cpp` and `hello.cpp` may also be used jointly for another executable, they may be put together in a library; replace the former `add_executable` command by: | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
add_library(hello_lib | ||
SHARED | ||
hello.cpp | ||
who-are-you.cpp) | ||
add_executable(hello | ||
main.cpp) | ||
target_link_libraries(hello | ||
hello_lib) | ||
``` | ||
%% Cell type:markdown id: tags: | ||
SHARED may be replaced by STATIC to use a static library instead. | ||
%% Cell type:markdown id: tags: | ||
You can run these commands directly with the ! symbol as follows: | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
!cd ./2c-Demo/7-CMake/ && mkdir build && cd build && cmake .. && make | ||
``` | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
!cd ./2c-Demo/7-CMake/build && ./hello | ||
``` | ||
%% Cell type:markdown id: tags: | ||
## Where should the headers be included? | ||
* Each time a header is modified, all the source files that include it directly or indirectly are recompiled. | ||
* Each time a source file is modified, only this source file is modified; some relinking for the libraries and executables that depend on it will also occur (linking is the step that glue together the object files and libraries; the term _compilation_ is often - included in this very tutorial - abusively used to encompass both compilation and link phases). | ||
Thus it might seem a good idea to put as much as possible `#include` directives in the source files **rather than in include files**... hence limiting the compilation time. This is a generally very good advice... provided we do not err on the wrong side and put enough in the header file: | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
// File foo.hpp | ||
#ifndef FOO_HPP | ||
# define FOO_HPP | ||
#include <string> | ||
void Print(std::string text); | ||
#endif // FOO_HPP | ||
``` | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
// File foo.cpp | ||
#include <iostream> | ||
#include "foo.hpp" | ||
void Print(std::string text) | ||
{ | ||
std::cout << "The text to be printed is: \"" << text << "\"." << std::endl; | ||
} | ||
``` | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
// File main.cpp | ||
#include <cstdlib> | ||
#include "foo.hpp" | ||
int main() | ||
{ | ||
Print("Hello world!"); | ||
return EXIT_SUCCESS; | ||
} | ||
``` | ||
%% Cell type:markdown id: tags: | ||
You may have noticed `string` and `iostream` are not dealt with the same way... and rightly so: | ||
* `#include <iostream>` is only in the source file: it is actually needed only for `std::cout` and `std::endl`, which are implementation details of `Print()` function: neither appears in the signature of the function. | ||
* `#include <string>` is present in `foo.hpp` as it is required to give the information about the type of the prototype to be used. If you do not do that, each time you include `foo.hpp` you would need to include as well `string`; doing so leads to unmaintainable code as you would have to track down all the includes that are required with each include... | ||
So to put in a nutshell: | ||
* Put in the header files all the includes that are mandatory to make the prototypes understandable. A rule of thumb is that a source file that would only include the header file should be compilable: | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
// File foo.hpp | ||
std::string Print(); | ||
``` | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
// File check_foo.cpp | ||
#include <cstdlib> | ||
#include "foo.hpp" | ||
int main(int, char**) | ||
{ | ||
return EXIT_SUCCESS; | ||
} // DOES NOT COMPILE => header is ill-formed! | ||
``` | ||
%% Cell type:markdown id: tags: | ||
* Include that are here for implementation details should on the other hand be preferably in source files. Of course, you may not be able to do that in any case: for instance templates are by construction defined in header files! | ||
%% Cell type:markdown id: tags: | ||
Some tools such as [include-what-you-use](https://include-what-you-use.org/) are rather helpful to help cut off the unrequired includes in file, but they need a bit of time to configure and set up properly, especially on an already large codebase. | ||
%% Cell type:markdown id: tags: | ||
## Forward declaration | ||
There is actually an exception to the first rule I've just given: **forward declaration**. This is really a trick that may be used to reduce compilation time, with some caveats. | ||
The idea is that if a type intervenes in a header file **only as a reference and/or as a (smart) pointer**, it might be forward-declared: its type is merely given in the header (`2c-Demo/11-Forward`) | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
// File foo.hpp | ||
#ifndef FOO_HPP | ||
# define FOO_HPP | ||
// Forward declaration: we say a class Bar is meant to exist... | ||
class Bar; | ||
struct Foo | ||
{ | ||
Foo(int n); | ||
void Print() const; | ||
Bar* bar_ = nullptr; | ||
}; | ||
#endif // FOO_HPP | ||
``` | ||
%% Cell type:code id: tags: | ||
``` C++17 | ||
``` c++ | ||
// File check_header_ok.cpp | ||
#include <cstdlib> | ||
#include "foo.hpp" | ||
int main(int, char**) | ||
{ | ||
return EXIT_SUCCESS; | ||
} | ||
``` | ||
%% Cell type:markdown id: tags: | ||
and `clang++ -std=c++17 check_header_ok.cpp` compiles properly (you may try commenting out the forward declaration line to check it does not without it) | ||
This is not without cost: obviously in a file where `Bar` is actually needed you will need to include it properly: with just `#include "foo.hpp"` you can't for instance call a method of `Bar` class. | ||
Typically the `include "bar.hpp"` will be located in the `foo.cpp` file, in which you will probably need the `Bar` object interface to define your `Foo` object (or if not you may question why you chose to put the `bar_` data attribute in the first place) | ||
It is nonetheless a very nice trick to know; there is even an idiom call [Pimpl idiom](https://arne-mertz.de/2019/01/the-pimpl-idiom/) that relies upon forward declaration. | ||
This is however not the only use for it though: to define a shared_ptr/weak_ptr you [also need](../7-Appendix/WeakPtr.ipynb) to use this capability. | ||
The tool [include-what-you-use](https://include-what-you-use.org/) mentioned earlier is able to suggest as well what should be forward-declared. | ||
%% Cell type:markdown id: tags: | ||
[© Copyright](../COPYRIGHT.md) | ||
... | ... |