2-FileStructure.ipynb 33.3 KB
Newer Older
1
2
3
4
5
6
{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
7
    "# [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)"
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "toc": true
   },
   "source": [
    "<h1>Table of contents<span class=\"tocSkip\"></span></h1>\n",
    "<div class=\"toc\"><ul class=\"toc-item\"><li><span><a href=\"#Library-and-program\" data-toc-modified-id=\"Library-and-program-1\">Library and program</a></span><ul class=\"toc-item\"><li><span><a href=\"#Static-and-shared-libraries\" data-toc-modified-id=\"Static-and-shared-libraries-1.1\">Static and shared libraries</a></span></li></ul></li><li><span><a href=\"#Source-file\" data-toc-modified-id=\"Source-file-2\">Source file</a></span><ul class=\"toc-item\"><li><span><a href=\"#Compilation-of-Hello-world!\" data-toc-modified-id=\"Compilation-of-Hello-world!-2.1\">Compilation of <em>Hello world!</em></a></span></li><li><span><a href=\"#Source-files-extensions\" data-toc-modified-id=\"Source-files-extensions-2.2\">Source files extensions</a></span></li><li><span><a href=\"#Expanding-our-hello-program-with-two-source-files:-one-for-main,-one-for-the-function\" data-toc-modified-id=\"Expanding-our-hello-program-with-two-source-files:-one-for-main,-one-for-the-function-2.3\">Expanding our hello program with two source files: one for main, one for the function</a></span></li></ul></li><li><span><a href=\"#Header-file\" data-toc-modified-id=\"Header-file-3\">Header file</a></span><ul class=\"toc-item\"><li><span><a href=\"#Header-location\" data-toc-modified-id=\"Header-location-3.1\">Header location</a></span></li><li><span><a href=\"#&quot;&quot;--or-<>?\" data-toc-modified-id=\"&quot;&quot;--or-<>?-3.2\"><code>\"\"</code>  or <code>&lt;&gt;</code>?</a></span></li><li><span><a href=\"#Header-guards\" data-toc-modified-id=\"Header-guards-3.3\">Header guards</a></span></li><li><span><a href=\"#Header-files-extensions\" data-toc-modified-id=\"Header-files-extensions-3.4\">Header files extensions</a></span><ul class=\"toc-item\"><li><span><a href=\"#My-personal-convention\" data-toc-modified-id=\"My-personal-convention-3.4.1\">My personal convention</a></span></li></ul></li></ul></li><li><span><a href=\"#Why-a-build-system:-very-basic-CMake-demonstration\" data-toc-modified-id=\"Why-a-build-system:-very-basic-CMake-demonstration-4\">Why a build system: very basic CMake demonstration</a></span></li><li><span><a href=\"#Where-should-the-headers-be-included?\" data-toc-modified-id=\"Where-should-the-headers-be-included?-5\">Where should the headers be included?</a></span></li><li><span><a href=\"#Forward-declaration\" data-toc-modified-id=\"Forward-declaration-6\">Forward declaration</a></span></li></ul></div>"
   ]
  },
  {
   "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",
30
    "* 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",
GILLES Sebastien's avatar
GILLES Sebastien committed
31
    "* 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",
32
33
34
35
36
    "\n",
    "### Static and shared libraries\n",
    "\n",
    "A (non header) library may be constructed as one of the following type:\n",
    "\n",
37
38
    "* 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",
39
    "\n",
40
    "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",
41
42
43
44
45
46
47
    "\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",
48
    "A source file is a type of file intended to be **compiled**.\n",
49
    "\n",
50
    "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"
51
52
53
54
   ]
  },
  {
   "cell_type": "code",
55
   "execution_count": null,
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
   "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 <iostream>\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",
95
    "- `-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",
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
    "- `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."
   ]
  },
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
  {
   "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"
   ]
  },
159
160
161
162
163
164
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Source files extensions\n",
    "\n",
165
    "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",
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
    "\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",
182
    "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",
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
    "\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 <iostream>\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 <cstdlib> // 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 <cstdlib> // 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 <iostream>\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": [
324
    "works as expected and creates a valid `hello` executable (also note the header file is not required explicitly in this build command)"
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
   ]
  },
  {
   "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",
GILLES Sebastien's avatar
GILLES Sebastien committed
387
388
389
390
391
392
    "* 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."
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
   ]
  },
  {
   "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 <cstdlib>\n",
    "#include \"foo.hpp\"\n",
424
    "#include \"foo.hpp\" // Oops...\n",
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
    "\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 <cstdlib>\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",
560
    "* End-user just includes the **.hpp** files in his code; he **never** needs to bother about including **.hxx** or not.\n",
561
    "* The **hpp** file is not too long and includes only declarations with additionally Doxygen comments to explain the API.\n",
GILLES Sebastien's avatar
GILLES Sebastien committed
562
563
    "\n",
    "And you may have noticed that standard library headers get no extension at all!\n"
564
565
566
567
568
569
570
571
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Why a build system: very basic CMake demonstration\n",
    "\n",
572
    "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",
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
    "\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 <string>\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 <iostream>\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 <iostream>\n",
    "#include \"who-are-you.hpp\"\n",
    "\n",
    "std::string WhoAreYou()\n",
    "{\n",
    "    std::string name;\n",
    "    std::cout << \"What's your name? \";\n",
640
    "    std::cin >> name; // not much safety here but this is not the current point!\n",
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
    "    return name;\n",
    "}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "// File main.cpp\n",
    "#include <cstdlib> // 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",
677
678
679
    "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",
680
681
682
683
684
685
686
    "clang++ -std=c++17 *.o -o hello          "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
687
    "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",
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
    "\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",
717
    "         // The directory indicated by .. MUST include the main CMakeLists.txt of the project.\n",
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
    "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 <string>\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 <iostream>\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 <cstdlib>\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 <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.\n",
    "* `#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...\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!"
   ]
  },
GILLES Sebastien's avatar
GILLES Sebastien committed
867
868
869
870
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
871
    "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."
GILLES Sebastien's avatar
GILLES Sebastien committed
872
873
   ]
  },
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
  {
   "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",
930
931
932
    "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."
933
934
935
936
937
938
939
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\n",
940
    "© _CNRS 2016_ - _Inria 2018-2021_   \n",
941
942
    "_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)_"
943
944
945
946
947
948
949
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "C++17",
   "language": "C++17",
950
   "name": "xcpp17"
951
952
953
954
955
956
  },
  "language_info": {
   "codemirror_mode": "text/x-c++src",
   "file_extension": ".cpp",
   "mimetype": "text/x-c++src",
   "name": "c++",
957
   "version": "17"
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
  },
  "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,
GILLES Sebastien's avatar
GILLES Sebastien committed
993
   "toc_window_display": false
994
995
996
997
998
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}