{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# [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", "metadata": { "toc": true }, "source": [ "

Table of contents

\n", "
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Library and program\n", "\n", "Contrary to for instance Python or Ruby, C++ is not a scripting language: it is intended to build either an **executable** or **library**.\n", "\n", "To summarize:\n", "\n", "* An **executable** runs the content of the [`main() function`](http://localhost:8888/notebooks/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.\n", "* 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**.\n", "\n", "### Static and shared libraries\n", "\n", "A (non header) library may be constructed as one of the following type:\n", "\n", "* 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! \n", "* 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...)\n", "\n", "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.\n", "\n", "## Source file\n", "\n", "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.\n", "\n", "### Compilation of _Hello world!_\n", "\n", "A source file is a type of file intended to be **compiled**.\n", "\n", "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):\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "// File hello.cpp - I put \"Code\" as cell type in Jupyter to get nice colors but it's not intended\n", "// to be executed in the cell!\n", "#include \n", "\n", "int main(int argc, char** argv)\n", "{\n", " std::cout << \"Hello world!\" << std::endl;\n", " \n", " return EXIT_SUCCESS;\n", "}" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "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", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "// In a terminal\n", "g++ -std=c++17 hello.cpp -o hello" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "where:\n", "\n", "- `g++` is the name of the compiler. You may provide clang++ if you wish.\n", "- `-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.\n", "- `hello.cpp` is the name of the source file.\n", "- `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", "metadata": {}, "source": [ "The executable may then be used with:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "// In a terminal\n", "./hello" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "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.\n", "\n", "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", "metadata": {}, "source": [ "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", "execution_count": 11, "metadata": {}, "outputs": [], "source": [ "!g++ -std=c++17 ./2c-Demo/1-HelloWorld/hello.cpp -o hello" ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Hello world!\n" ] } ], "source": [ "!./hello" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Source files extensions\n", "\n", "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. \n", "\n", "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).\n", "\n", "The most common extensions are **.cpp**, **.cc**, **.C** and more seldom **.cxx**.\n", "\n", "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", "metadata": {}, "source": [ "### Expanding our hello program with two source files: one for main, one for the function\n", "\n", "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.\n", "\n", "You may imagine working in a single file is not an very common option: it hinders reusability, and it would be cumbersome to navigate in a file with thousands or more lines or code (if you're really curious to 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...)\n", "\n", "We want know to separate the main() and the actual content of the code:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "// File hello.cpp - no main inside\n", "#include \n", "\n", "void hello()\n", "{\n", " std::cout << \"Hello world!\" << std::endl;\n", "}\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "// File main.cpp\n", "#include // for EXIT_SUCCESS\n", "\n", "int main(int argc, char** argv)\n", "{\n", " hello();\n", " \n", " return EXIT_SUCCESS;\n", "}" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This brute force method is not working: a line on a terminal like:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "// In a terminal\n", "clang++ -std=c++17 hello.cpp main.cpp -o hello" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "would yield something like:\n", "\n", "````verbatim\n", "main.cpp:5:5: error: use of undeclared identifier 'hello'\n", " hello();\n", " ^\n", "1 error generated.\n", "````" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Header file\n", "\n", "The issue above is that we need to inform the compiler when it attemps 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:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "// File hello.hpp\n", "void hello();" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "// File main.cpp\n", "#include // for EXIT_SUCCESS\n", "#include \"hello.hpp\"\n", "\n", "int main(int argc, char** argv)\n", "{\n", " hello();\n", " \n", " return EXIT_SUCCESS;\n", "}" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "// File hello.cpp - no main inside\n", "#include \n", "#include \"hello.hpp\"\n", "\n", "void hello()\n", "{\n", " std::cout << \"Hello world!\" << std::endl;\n", "}" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "With this few changes, the command line:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "// In a terminal\n", "clang++ -std=c++17 hello.cpp main.cpp -o hello" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "works as expected and creates a valid `hello` executable (also note the header file is not required explicitly in this build command)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Header location\n", "\n", "In the example above `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:\n", "\n", "* Either modifying the path in the source file. We would get\n", "\n", "````#include \"incl/hello.hpp\"```` in both hello.cpp and main.cpp.\n", "\n", "* Or by giving to the command line the `-I` instruction to indicate which path to look for:\n", "\n", "\n", "\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "// In a terminal\n", "clang++ -std=c++17 -Iincl hello.cpp main.cpp -o hello" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "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:\n", "\n", "\n", "````verbatim\n", "incl/foo.hpp\n", "bar/incl/foo.hpp\n", "````\n", "\n", "and \n", "\n", "````\n", "clang++ -Iincl -Ibar/incl main.cpp\n", "````\n", "\n", "leads to an ambiguity if there is `#include \"foo.hpp\"` in the `main.cpp`...\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### `\"\"` or `<>`?\n", "\n", "You may have noticed I sometimes used `<>` and sometimes `\"\"` to specify the path for the include.\n", "\n", "The details don't matter that much in most cases, but it is better to:\n", "\n", "* Use `<>` only for the system libraries, typically STL or C headers should be this form.\n", "* Use `\"\"` for your headers or for third-party libraries installed in specific locations.\n", "\n", "If you want a bit more details:\n", "\n", "* `\"\"` will look first in the current directory, and then in the header files directories.\n", "* `<>` will look only in the header files directories." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Header guards\n", "\n", "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:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "// File foo.hpp\n", "class Foo\n", "{ };" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "// File main.cpp\n", "#include \n", "#include \"foo.hpp\"\n", "#include \"foo.hpp\" // Oops...\n", "\n", "int main()\n", "{\n", " \n", " return EXIT_SUCCESS;\n", "}" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "doesn't compile: the translation unit provides two declarations of class Foo!\n", "\n", "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:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "// File foo.hpp\n", "class Foo\n", "{ };" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "// File bar.hpp\n", "\n", "#include \"foo.hpp\"\n", "\n", "struct Bar\n", "{\n", " Foo foo_;\n", "};" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "// File main.cpp\n", "#include \n", "#include \"foo.hpp\"\n", "#include \"bar.hpp\" // Compilation error: \"foo.hpp\" is sneakily included here as well!\n", "\n", "int main()\n", "{\n", " \n", " return EXIT_SUCCESS;\n", "}" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The patch is to indicate in each header file that it should be included only once. There is the easy but non standard approach I honestly didn't know up to now was [so widely supported](https://en.wikipedia.org/wiki/Pragma_once#Portability) by compilers:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "// File foo.hpp - Fix 1\n", "#pragma once\n", "\n", "class Foo\n", "{ };" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "And the more tedious one called **header guards** which is fully supported by the standard but much more clunky:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "#ifndef FOO_H // If this macro is not yet defined, proceed to the rest of the file.\n", "# define FOO_H // Immediately define it so next call won't include again the file content.\n", "\n", "class Foo\n", "{ };\n", "\n", "#endif // FOO_H // End of the macro block that begun with #ifndef" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "\n", "To make that work in a program, you have to ensure that:\n", "\n", "* Each macro name is unique: if `bar.hpp` also defines #ifndef FOO_H, one of the file will never be included!\n", "* The macros should not have been defined elsewhere in another context.\n", "\n", "In my code, to ensure the first never happen, I have written a [Python script](https://gitlab.inria.fr/MoReFEM/CoreLibrary/MoReFEM/raw/master/Scripts/header_guards.py) which iterates through all the C++ files in my 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. So definitely much more clunky than **#pragma once** ! But as I 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", "metadata": {}, "source": [ "### Header files extensions\n", "\n", "The most current header files extensions are **.hpp**, **.h**, **.hh** and more seldom **.hxx**. I definitely 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.\n", "\n", "#### My personal convention\n", "\n", "Personally I am using both **.hpp** and **.hxx**:\n", "\n", "* **.hpp** is for the declaration of functions, classes, and so on.\n", "* **.hxx** is for the definitions of inline functions and templates.\n", "\n", "The **.hxx** is included at the end of **.hpp** file; this way:\n", "\n", "* End-user just includes the **.hpp** files in his code; he **never** needs to bother about including **.hxx** or not.\n", "* The **hpp** file is not too long and includes only declarations with additionally Doxygen comments to explain the API.\n", "\n", "And you may have noticed that standard library headers get no extension at all!\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Why a build system: very basic CMake demonstration\n", "\n", "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:\n", "\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "// File hello.hpp\n", "#ifndef HELLO_HPP\n", "#define HELLO_HPP\n", "\n", "void hello();\n", "\n", "#endif // HELLO_HPP" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "// File who-are-you.hpp\n", "#ifndef WHO_ARE_YOU_H\n", "#define WHO_ARE_YOU_H\n", "\n", "#include \n", "\n", "std::string WhoAreYou();\n", "\n", "#endif // WHO_ARE_YOU_H" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "// File hello.cpp\n", "#include \n", "#include \"hello.hpp\"\n", "#include \"who-are-you.hpp\"\n", "\n", "void hello()\n", "{\n", " auto identity = WhoAreYou();\n", " std::cout << \"Hello \" << identity << std::endl;\n", "}\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "// File who-are-you.cpp\n", "#include \n", "#include \"who-are-you.hpp\"\n", "\n", "std::string WhoAreYou()\n", "{\n", " std::string name;\n", " std::cout << \"What's your name? \";\n", " std::cin >> name; // not much safety here but this is not the current point!\n", " return name;\n", "}" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "// File main.cpp\n", "#include // For EXIT_SUCCESS\n", "#include \"hello.hpp\"\n", "\n", "int main(int argc, char** argv)\n", "{\n", " hello();\n", " \n", " return EXIT_SUCCESS;\n", "}" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Up to now, we compiled such a program with manually:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "// In terminal\n", "clang++ -std=c++17 -c hello.cpp\n", "clang++ -std=c++17 -c main.cpp\n", "clang++ -std=c++17 -c who-are-you.cpp\n", "clang++ -std=c++17 *.o -o hello " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "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.\n", "\n", "It is to handle automatically this and limit the compilation to only what is required that build systems (which we talked about briefly [here](/notebooks/6-InRealEnvironment/1-SetUpEnvironment.ipynb#Build-system)) were introduced. Let's see a brief CMake configuration file named by convention `CMakeLists.txt`:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "// CMakeLists.txt\n", "set(CMAKE_CXX_STANDARD 17 CACHE STRING \"C++ standard; at least 17 is expected.\")\n", "\n", "add_executable(hello\n", " main.cpp \n", " hello.cpp \n", " who-are-you.cpp)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "// In terminal\n", "mkdir build // create a directory to separate build from source files and so on\n", "cd build\n", "cmake .. // will create the Makefile; as no generator was provided with -G Unix makefile is chosen.\n", " // The directory indicated by .. MUST include the main CMakeLists.txt of the project.\n", "make" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "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", "metadata": {}, "source": [ "If `main.cpp` and `hello.cpp` may also be used jointly for another executable, they may be put together in a library:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "set(CMAKE_CXX_STANDARD 17 CACHE STRING \"C++ standard; at least 17 is expected.\")\n", "\n", "add_library(hello_lib\n", " SHARED\n", " hello.cpp \n", " who-are-you.cpp)\n", "\n", "\n", "add_executable(hello\n", " main.cpp)\n", " \n", "target_link_libraries(hello \n", " hello_lib) " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "SHARED may be replaced by STATIC to use a static library instead." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Where should the headers be included?\n", "\n", "* Each time a header is modified, all the source files that include it directly or indirectly are recompiled. \n", "* 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).\n", "\n", "Thus it might seem a good idea to put as much as possible `#include` directives in the source 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", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "// File foo.hpp\n", "#ifndef FOO_HPP\n", "# define FOO_HPP\n", "\n", "#include \n", "\n", "void Print(std::string text);\n", "\n", "#endif // FOO_HPP" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "// File foo.cpp\n", "#include \n", "#include \"foo.hpp\"\n", "\n", "void Print(std::string text)\n", "{\n", " std::cout << \"The text to be printed is: \\\"\" << text << \"\\\".\" << std::endl;\n", "}" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "// File main.cpp\n", "#include \n", "#include \"foo.hpp\"\n", "\n", "int main()\n", "{\n", " Print(\"Hello world!\");\n", " \n", " return EXIT_SUCCESS;\n", "}\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "You may have noticed `string` and `iostream` are not deal with the same way... and rightly so:\n", "\n", "* `#include ` 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.\n", "* `#include ` 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...\n", "\n", "So to put in a nutshell:\n", "\n", "* 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:\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "// File foo.hpp\n", "std::string Print();" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "// File check_foo.hpp\n", "#include \"foo.hpp\" // DOES NOT COMPILE => header is ill-formed!" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "* Include that are here for implementation details should on the other hand be preferrably 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", "metadata": {}, "source": [ "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", "metadata": {}, "source": [ "## Forward declaration\n", "\n", "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.\n", "\n", "The idea is that if a type intervenes in a header file **only as a reference and/or as a (smart) pointer**, if might be forward-declared: its type is merely given in the header.\n", "\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "// File foo.hpp\n", "\n", "#ifndef FOO_HPP\n", "# define FOO_HPP\n", "\n", "// Forward declaration: we say a class Bar is meant to exist...\n", "class Bar;\n", "\n", "struct Foo\n", "{\n", " Foo(int n);\n", " \n", " void Print() const;\n", "\n", " Bar* bar_ = nullptr;\n", "};\n", "\n", "#endif // FOO_HPP" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "// File check_header_ok\n", "#include \"foo.hpp\"" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "and `clang++ -std=c++17 -c foo_only.cpp` compiles properly.\n", "\n", "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`. 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.\n", "\n", "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.\n", "\n", "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", "metadata": {}, "source": [ "\n", "© _CNRS 2016_ - _Inria 2018-2021_ \n", "_This notebook is an adaptation of a lecture prepared by David Chamont (CNRS) under the terms of the licence [Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0)](http://creativecommons.org/licenses/by-nc-sa/4.0/)_ \n", "_The present version has been written by Sébastien Gilles and Vincent Rouvreau (Inria)_" ] } ], "metadata": { "kernelspec": { "display_name": "C++17", "language": "C++17", "name": "xcpp17" }, "language_info": { "codemirror_mode": "text/x-c++src", "file_extension": ".cpp", "mimetype": "text/x-c++src", "name": "c++", "version": "17" }, "latex_envs": { "LaTeX_envs_menu_present": true, "autoclose": false, "autocomplete": true, "bibliofile": "biblio.bib", "cite_by": "key", "current_citInitial": 1, "eqLabelWithNumbers": true, "eqNumInitial": 1, "hotkeys": { "equation": "Ctrl-E", "itemize": "Ctrl-I" }, "labels_anchors": false, "latex_user_defs": false, "report_style_numbering": false, "user_envs_cfg": false }, "toc": { "base_numbering": 1, "nav_menu": {}, "number_sections": false, "sideBar": true, "skip_h1_title": true, "title_cell": "Table of contents", "title_sidebar": "Contents", "toc_cell": true, "toc_position": { "height": "calc(100% - 180px)", "left": "10px", "top": "150px", "width": "279px" }, "toc_section_display": true, "toc_window_display": false } }, "nbformat": 4, "nbformat_minor": 2 }