-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathcpp.php
More file actions
1057 lines (713 loc) · 24.3 KB
/
cpp.php
File metadata and controls
1057 lines (713 loc) · 24.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
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
95
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
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
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
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
324
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
387
388
389
390
391
392
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
424
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
560
561
562
563
564
565
566
567
568
569
570
571
572
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
640
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
677
678
679
680
681
682
683
684
685
686
687
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
717
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
867
868
869
870
871
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
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
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
993
994
995
996
997
998
999
1000
<?php include 'header.php';?>
<h1>The Preprocessor (2/5)</h1>
<a class="arrow" href="driver.php">←</a> <a class="arrow" href="cc.php">→</a>
<hr/>
<div style="width:30%;float: right; margin-left: 2ch; margin-bottom: 2ch;">
<table class="lined" style="width: 100%; text-align: center; margin-top: 0;">
<tr>
<td colspan="3">driver
</td><td style="border-top-style: hidden; border-right-style: hidden;"></td>
</tr>
<tr>
<td>cpp<span class="r">*</span></td>
<td>cc</td>
<td>ld</td>
<td>loader</td>
</tr>
</table>
</div>
<p style="margin-top: 0;">
In this chapter, we no longer focus on the compiler driver. Instead we take a look at the first stage of the compilation pipeline, the preprocessor.
</p>
<p>
The goal of the preprocessor is to ingest one source file to resolve all its header files dependencies, resolve all macros, and output a translation unit that will be consumed by the compiler in the next stage. The preprocessor usually takes care of a source file (<code>.c</code>/<code>.cc</code>/<code>.cpp</code>/<code>.m</code>/<code>.mm</code>) but it is language agnostic. It can process anything, even text files, as long as it detects "directives" (commands starting with <code>#</code> character).
</p>
<h2>Is it <code>cpp</code> or <code>-E</code> ?</h2>
<p>
In the early days, the preprocessor was a separate executable called <code>cpp</code> (<b>C</b> <b>P</b>re<b>P</b>rocessor). Lucky us, developers have maintained it all these years, and we can still invoke it.
</p>
<pre><b>$</b> <span class="r">cpp</span> hello.c -o hello.tu
</pre>
<p>Just kidding. Using verbose mode shows that it is once again the compiler driver which uses <code>argv[0]</code> to detect it should invoke itself with <code>-E</code> parameter to behave like a preprocessor.
</p>
<pre>
<b>$</b> <span class="r">cpp</span> -v hello.c -o hello.tu
clang -cc1 <span class="r">-E</span> -o hello.tu hello.c
</pre>
<div class="t">The extension used by compilers to store translation units can be <code>.i</code>, <code>.ii</code>, <code>.mi</code>, or even <code>.mii</code>. For simplicity, we always use <code>.tu</code>.</div>
<h2>How much pre-processing occurs?</h2>
<p>
A lot of work is done by <code>cpp</code>! So much in fact that the preprocessor is a bottleneck in big projects. Just to get an idea, see how the six lines in hello.c become a behemoth 748 lines translation unit.
</p>
<pre><b>$</b> <span class="r">wc -l</span> hello.c
<span class="r">6</span> hello.c</pre>
<pre><b>$</b> cpp hello.c > hello.tu
<b>$</b> <span class="r">wc -l</span> hello.tu
<span class="r">748</span> hello.tu</pre>
<div class="t"> Including whole headers for each translation unit generation is a repeating task that is wasteful. Not only a huge volume of lines is involved, each of them are tokenized by <code>cpp</code>. C++ modules should solve this problem. They are not available yet but we should have them soon, right after hell freezes over.
</div>
<h2>Peeking inside a translation unit</h2>
<p>Let's look inside a translation unit.
</p>
<pre><b>$</b> cpp hello.c > hello.tu
<b>$</b> cat hello.tu
<span class="r"># 328 "/usr/include/stdio.h" 3 4</span>
extern int <span class="b">printf</span> (const char *__restrict __format, ...);
... // many hundred more lines
<span class="r"># 2 "hello.c" 2</span>
main()
{
<span class="b">printf</span>("hello, world\n");
}
</pre>
<p> Each fragment of code is preceded by a comment <code># linenum filename flags</code> allowing to backtrack which file it came from. This allows the compiler to issue error messages with accurate line numbers.</p>
<h2>Directives, the preprocessor language</h2>
<p>
All directives aimed at the preprocessor are prefixed with <code>#</code>. The names are usually self-explanatory. You can among many features include files, declare macro, perform conditional compilation.
<div class="t">
The preprocessor is regularly abused. It is so powerful that you can use it to have C program look like Java.
<pre>#include <iostream>
#define System S s;s
#define public
#define static
#define void int
#define main(x) main()
struct F{void println(char* s){std::cout << s << std::endl;}};
struct S{F out;};
public static void main(String[] args) {
System.out.println("Hello World!");
}
</pre>
</div>
<p>
A handy feature of the pre-processor is the ability to receive command-line parameters to define values via the <code>-D</code> flag. Let's build a modified hello world.
</p>
<pre>// defined_return_code.c
int main() {
return <span class="r">RETURN_VALUE</span>;
}</pre>
<p>Let's compile it while defining <code>RETURN_VALUE</code> with <code>-DRETURN_VALUE=3</code>
<pre><b>$</b> clang <span class="r">-DRETURN_VALUE=3</span> defined_return_code.c
<b>$</b> ./a.out ; echo $?
<span class="r">3</span>
</pre>
<div class="t">
VLC is an immensely popular open source video player entirely written in C. It uses the pre-processor macros to implement <code>struct</code> inheritance.
<pre>/* VLC_COMMON_MEMBERS : members common to all basic vlc objects */
#define <span class="r">VLC_COMMON_MEMBERS</span> \
const char *psz_object_type; \
\
/* Messages header */ \
char *psz_header; \
int i_flags; \
\
struct libvlc_int_t {
<span class="r">VLC_COMMON_MEMBERS</span>
/* Everything Else */
}
</pre>
</div>
<h2>Why headers are needed</h2>
<p>When C was created, in the 70s, memory was severely limited. So much so that it constrained compilers to emit instructions after a single pass over a source file. To achieve one pass emission, the language designers pushed the constraint on the programmer.
</p>
<p>All functions and variables must be declared before using them. Their definition could come later.</p>
<pre>
int mul(int x, int y); // This is a declaration
int mul(int x, int y) <span class="r">{ return x * y;}</span> // This is a definition (and also a declaration)
extern int i; // This is a declaration
int i = 0 ; // This is a definition (and also a declaration)
class A; // This is a (forward) declaration
class A {}; // This is a definition (and also a declaration)
</pre>
Let's see what happens when we disregard this constraint.
</p>
<pre>// var_err.c
int main() {
return v;
}
int v = 0;
</pre>
<p> In this example, despite variable <code>v</code> being defined three lines later, the compiler will emit and error when <code>main</code> attempts to use it.</p>
<pre>
<b>$</b> clang var_err.c
<span class="r">var_err.c:2:10: error: use of undeclared identifier 'v'</span>
</pre> <p>
In the case of function invocation, the compiler not only needs to know the return type but also the parameters a function expects (a.k.a its signature). It does not matter if the actual method body (definition) comes after as long as the parameters and their types are known when the callsite must be issued.
</p>
<pre>// bad_fibonacci.c
int fibonacci(int n) {
if (n <= 1)
return n;
return fibonacci(n - 1) + fibonacci(n - 2);
}
</pre>
<pre>
<b>$</b> clang -c bad_fibonacci.c
<span class="r">bad_fibonacci.c:4:12: error: implicit declaration of function 'fibonacci' is invalid in C99</span>
</pre>
<p><code>bad_fibonacci</code> did not declare the function <code>fibonacci</code> before using it which resulted in an error.</p>
<pre>// good_fibonacci.c
<span class="r">int fibonacci(int n);</span>
int fibonacci(int n) {
if (n <= 1)
return n;
return fibonacci(n - 1) + fibonacci(n - 2);
}</pre>
<p>Adding the declaration allows the compiler to work in one pass.</p>
<pre>
<b>$</b> clang -c good_fibonacci.c // It worked
</pre>
<h2>Things get complicated</h2>
<p>The rule of definition before usage is simple but inconvenient to follow. Sometimes it is plain impossible when two functions call each other.
</p>
<pre>
int <span class="r">function1</span>(int x) {
if (x) return <span class="b">function2</span>(2);
return 1;
}
int <span class="b">function2</span>(int x) {
if (x) return <span class="r">function1</span>(2);
return 2;
}</pre>
<p>The solution is to adopt a convention where declarations are put in header files and the definitions in the source files. This way, programmers are free to organize their source code as they please.</p>
<table style="width: 100%;">
<tr>
<td>
<pre>// foo.h
int <span class="r">mul</span>(int x, int y);
int <span class="g">sub</span>(int x, int y);
</pre>
</td>
<td>
<pre>// bar.h
int <span class="k">div</span>(int x, int y);
int <span class="b">add</span>(int x, int y);
</pre>
</td>
</tr>
<tr>
<td>
<pre>// foo.c
#include "foo.h"
#include "bar.h"
int <span class="r">mul</span>(int x, int y) {
int c = x;
while(y--) // mul with add!
c = <span class="b">add</span>(1, c);
return c;
}
int <span class="g">sub</span>(int x, int y) {
return x - y;
}
</pre>
</td>
<td>
<pre>// bar.c
#include "bar.h"
#include "foo.h"
int <span class="k">div</span>(int x, int y) {
int c = x;
while(y--) // div with sub!
x = <span class="g">sub</span>(x, 1);
return c;
}
int <span class="b">add</span>(int x, int y) {
return x + y;
}
</pre>
</td>
</tr>
</table>
<p>
We can verify that this technique makes sense by looking at <code>cpp</code> outputs.
<p>
<pre>
$ <span class="r">cpp</span> foo.c > foo.tu
$ <span class="r">cpp</span> bar.c > bar.tu
</pre>
<p>
Notice how all comments have been removed and the macros resolved. All that remains is pure code. And of course, all functions are declared before being used.
</p>
<table style="width: 100%;">
<tr>
<td>
<pre>// foo.tu
int <span class="r">mul</span>(int x, int y);
int <span class="b">add</span>(int x, int y);
int <span class="k">div</span>(int x, int y);
int <span class="g">sub</span>(int x, int y);
int <span class="r">mul</span>(int x, int y) {
int c = x;
while(y--)
c = <span class="b">add</span>(1, c);
return c;
}
int <span class="b">add</span>(int x, int y) {
return x + y;
}
</pre>
</td>
<td>
<pre>// bar.tu
int <span class="k">div</span>(int x, int y);
int <span class="g">sub</span>(int x, int y);
int <span class="r">mul</span>(int x, int y);
int <span class="b">add</span>(int x, int y);
int <span class="k">div</span>(int x, int y) {
while(y--)
x = <span class="g">sub</span>(x, 1);
return c;
}
int <span class="g">sub</span>(int x, int y) {
return x - y;
}
</pre>
</td>
</tr>
</table>
<h2>Header guards</h2>
<p>
So far, it looks like the header system works well. Each source file becomes a translation unit with all declarations at the top. But this technique has a flaw if a header ends up being included more than once. Let's take the example of a mini game-engine project.
</p>
<table>
<tr>
<td>
<pre>// engine.h
struct World {
};
</pre>
</td>
<td>
<pre>// ai.h
#include "engine.h"
void think(World& world);
</pre>
</td>
<td>
<pre>// render.h
#include "engine.h"
void render(World& world);
</pre>
</td>
</tr>
<tr>
<td>
<pre>// engine.cc
#include "engine.h"
#include "render.h"
#include "ai.h"
void hostFrame(World& world) {
think(world);
render(world);
}
</pre>
</td>
<td>
<pre>// ai.cc
#include "ai.h"
void think(World& world) {
}
</pre>
</td>
<td>
<pre>// render.cc
#include "render.h"
void render(World &worldv) {
}
</pre>
</td>
</tr>
</table>
<p>If we attempt to generate each object file, the sub-systems <code>ai.cc</code> and <code>render.cc</code> compile fine but <code>engine.cc</code> throws an error.
</p>
<pre><b>$</b> clang -c -o render.o render.cc
<b>$</b> clang -c -o ai.o ai.cc
<b>$</b> clang -c -o engine.o engine.cc
In file included from engine.cc:4:
In file included from ./render.h:3:
<span class="r">./engine.h:3:8: error: redefinition of 'World'
struct World {
^</span>
engine.cc:3:10: note: './engine.h' included multiple times, additional include site here
#include "engine.h"
^
./render.h:3:10: note: './engine.h' included multiple times, additional include site here
#include "engine.h"
^
./engine.h:3:8: note: unguarded header; consider using #ifdef guards or #pragma once
struct World {
^
In file included from engine.cc:5:
In file included from ./ai.h:3:
<span class="r">./engine.h:3:8: error: redefinition of 'World'
struct World {
^</span>
engine.cc:3:10: note: './engine.h' included multiple times, additional include site here
#include "engine.h"
^
./ai.h:3:10: note: './engine.h' included multiple times, additional include site here
#include "engine.h"
^
./engine.h:3:8: note: unguarded header; consider using #ifdef guards or #pragma once
struct World {
^
2 errors generated.
</pre>
<p>
Inspecting the resulting TUs with <code>cpp</code> shows the problem.
</p>
<table>
<tr>
<td>
<pre><b>$</b> cpp engine.cc
<span class="r">struct World {
};</span>
<span class="r">struct World {
};</span>
void render(World& world);
<span class="r">struct World {
};</span>
void think(World& world);
void hostFrame(World& world) {
think(world);
render(world);
}
</pre>
</td>
<td>
<pre><b>$</b> cpp ai.cc
struct World {
};
void think(World& world);
void think(World& world) {
}
</pre>
</td>
<td>
<pre><b>$</b> cpp render.cc
struct World {
};
void render(World& world);
void render(World &world) {
}
</pre>
</td>
</tr>
</table>
<p><code>engine.cc</code> includes <code>engine.h</code>. However <code>engine.cc</code> also includes <code>ai.h</code> which in turns also includes <code>engine.h</code>. In the final <code>cpp</code>ed translation unit, <code>engine.h</code> is included three times and the struct <code>World</code> is declared three times as well.
</p>
<p>
The solution to multiple import and import cycles is to use include guards or <code>pragma</code> guard. The difference between the two is that pragma is not part of the standard (although widely supported).
</p>
<table>
<tr>
<td>
<pre>// engine.h
<span class="r">#pragma once</span> // Pragma guard
struct World {
};
</pre>
</td>
<td>
<pre>// ai.h
<span class="r">#ifndef AI.H</span> // Header guard
<span class="r">#define AI.H</span>
#include "engine.h"
void think(World& world);
<span class="r">#endif </span> // AI.H
</pre>
</td>
<td>
<pre>// render.h
<span class="r">#ifndef RENDERER.H</span> // Header guard
<span class="r">#define RENDERER.H</span>
#include "engine.h"
void render(World& world);
<span class="r">
#endif</span> // RENDERER.H
</pre>
</td>
</tr>
<tr>
<td>
<pre>// engine.cc
#include "engine.h"
#include "render.h"
#include "ai.h"
void hostFrame(World& world) {
think(world);
render(world);
}
</pre>
</td>
<td>
<pre>// ai.cc
#include "ai.h"
void think(World& world) {
}
</pre>
</td>
<td>
<pre>// render.cc
#include "render.h"
void render(World &worldv) {
}
</pre>
</td>
</tr>
</table>
<p>Since we now prevent multiple header inclusion in the same TU, we can compile the whole project.</p>
<pre><b>$</b> clang -c -o render.o render.cc
<b>$</b> clang -c -o ai.o ai.cc
<b>$</b> clang -c -o engine.o engine.cc
<b>$</b>
</pre>
<h2>Precompiled headers (PCH)</h2>
<p>
As we alluded earlier while <code>wc</code>ing the outputs of <code>cpp</code>, the volume resulting from <code>#include</code> is huge. It is even worse in C++ where <code>hello.cc</code> 6 lines turned into 44,065 lines, a whopping 7,344% increase.
</p>
<p>
It is a non-trivial amount of work to parse all this text, even with modern Threadripper CPUs. Build time can be reduced by using pre-compiled headers.
</p>
<pre>// all_header.h
#include "engine.h"
#include "ai.h"
#include "render.h"
</pre>
<p>Precompiled headers are super header containing all other headers and stored in binary form.
</p>
<pre><b>$</b> clang -cc1 all_header.h <span class="r">-emit-pch</span> -o <span class="r">all_header.pch</span>
</pre>
<p>With this approach, the source code does not need to <code>#include</code> anything anymore.
<table>
<tr>
<td>
<pre>// engine.cc
void hostFrame(World& world) {
think(world);
render(world);
}
</pre>
</td>
<td>
<pre>// ai.cc
void think(World& world) {
}
</pre>
</td>
<td>
<pre>// render.cc
void render(World &world) {
}
</pre>
</td>
</tr>
</table>
<p>Compiling requires to give the path to the precompiled header to the driver.
</p>
<pre><b>$</b> clang -v <span class="r">-include-pch all_header.pch</span> -c render.cc ai.cc engine.cc
</pre>
<h2>Header Search Path</h2>
<p>
By default, the preprocessor first attempts to locate the target of <code>#include</code> directives in the same directory as the source file. If that fails, the preprocessor goes though the "header search path". Let's take the example of a simple <code>hello_world.c</code> project which uses an include for the string value to <code>printf</code>
</p>
<table>
<tr>
<td>
<pre>// hello_with_include.c
#include "stdio.h"
#include "hello_with_include.h"
int main() {
printf(MESSAGE);
return 0;
}
</pre>
</td>
<td>
<pre>// include_folder/hello_with_include.h
#define MESSAGE "Hello World!\n"
</pre>
</td>
</tr>
</table>
<p>If the header is not in the same directory, it cannot be found by the pre-processor. We get an error.</p>
<pre><b>$</b> find .
hello_with_include.c
<span class="h">include_folder/</span>hello_with_include.h
<b>$</b> clang hello_with_include.c
<span class="r">hello_with_include.c:2:10: fatal error: 'hello_with_include.h' file not found
#include "hello_with_include.h"
^~~~~~~~~~~~~~~~~~~~~~</span>
</pre>
<p>
The algorithm to lookup the header search path is quite elaborated but well described on GNU gcc <a href="https://gcc.gnu.org/onlinedocs/gcc/Directory-Options.html">cpp documentation</a> page. To fix our example, we can add a directory to the path to search via <code>-I</code>.
</p>
<pre><b>$</b> clang <span class="r">-Iinclude_folder</span> hello_with_include.c
</pre>
<p>
There are many more flags that can be passed to the driver to impact the header search path. Among them, <code>-sysroot</code>, <code>-iquote</code>, <code>-isystem</code> which impacts vary whether an <code>#include</code> directive uses quotes <code>"</code> or angled brackets (<code><</code> <code>></code>). There is even a <code>-sysroot</code> parameter which defines a whole toolchain featuring both the header search path and the library linker search path.
</p>
<h3>Headers provided by the compiler toolchain</h3>
<p>Some headers are not provided via flags. These come with the compiler and are automatically added to the header search path. It is the case of <code>stddef.h</code> which provides among other things <code>size_t</code> definition and the <code>NULL</code> macro.
</p>
<pre><b>$</b> cat someheader.h
#include "stddef.h"
<b>$</b> gcc <span class="r">-E</span> someheader.h
<span class="r"># 1 "/usr/lib/gcc/aarch64-linux-gnu/11/include/stddef.h" 1 3 4</span>
<b>$</b> clang <span class="r">-E</span> someheader.h
<span class="r"># 1 "/usr/lib/llvm-14/lib/clang/14.0.0/include/stddef.h" 1 3</span>
<b>$</b></pre>
<h2>Header dependency graph and build systems</h2>
<p>Build system compile source files over and over again. An obvious optimization is to re-use outputs from previous runs if they did not change.
But because of the header search path and the undeclared preprocessor dependencies, it is hard to build a reliable dependency graph.
</p>
<p>
This problem can be solved by asking the pre-processor which files were accessed while preprocessing. With <code>clang</code> for example, the flag <code>-MD</code> requests the preprocessor to output the dependency required to generate a translation unit. A further option <code><code>-MF</code></code> instructs to write the output to a file. Note that these options can be fed to the compiler driver which will forward them to the pre-processor.
</p>
<pre>$ cat hello.c
#include <stdio.h>
int main() {
printf("Hello, world!\n");
return 0;
}
$ clang <span class="r">-MD -MF hello.d</span> -c -o hello.o hello.c
$ cat hello.d
hello.o: hello.c /usr/include/stdio.h /usr/include/_types.h
/usr/include/sys/_types.h /usr/include/sys/cdefs.h
/usr/include/machine/_types.h /usr/include/i386/_types.h
/usr/include/secure/_stdio.h /usr/include/secure/_common.h
</pre>
<div class="t"> The notoriously blazing fast build system <code>ninja</code> leverages these dependencies outputs to create a dependency graph. After the first compilation, the dependency graph is parsed. On each subsequent build, file modification timestamps are checked to re-build only what has changed.
</div>
<h2>Header discipline</h2>
<p><code>cpp</code> will not warn programmers if they neglect to keep their headers tidy. As much as possible, try to:
<ul>
<li>Avoid transitive dependencies.</li>
<li>Not expose implementation details.</li>
</ul>
</p>
<p>The following header system exhibits the problems when these two rules are not followed.</p>
<table>
<tr>
<td>
</td>
</td>
<td>
<pre>// utils.h
#pragma once
<span class="r">#include <stdlib.h></span>
char* getBuffer(int size);
</pre>
</td>
</tr>
<tr>
<td>
<pre>// main.c
#include "utils.h"
#include <stdio.h>
int main() {
char* buffer = getBuffer(10);
// do stuff ...
free(buffer);
return 0;
}
</pre>
</td>
<td>
<pre>// utils.c
char* getBuffer(int size) {
return (char*)calloc(size);
}
</pre>
</td>
</tr>
</table>
<p>Header <code>utils.h</code> includes <code>stdlib.h</code> but it is wasteful. All source files including <code>utils.h</code> now have to also include <code>stdlib.h</code>. Moreover, the fact that <code>utils.c</code> uses <code>calloc</code> is an implementation detail. Let's refactor this line.</p>
<table>
<tr>
<td>
</td>
<td>
<pre>// util.h
#pragma once
char* getBuffer(int size);
</pre>
</td>
</tr>
<tr>
<td>
<pre>// main.c
#include "utils.h"
#include <stdio.h>
int main() {
char* buffer = getBuffer(10);
// do stuff ...
free(buffer);
return 0;
}
</pre>
</td>
<td>
<pre>// util.c
<span class="r">#include <stdlib.h></span>
char* getBuffer(int size) {
return (char*)calloc(size);
}
</pre>
</td>
</tr>
</table>
<p>Moving <code>stdlib.h</code> include from the <code>.h</code> file to the <code>.c</code> file keeps the implementation details private. Let's see what happens when we try to compile.</p>
<pre><b>$</b> clang -o main main.c utils.c
<span class="r">main.c:2:3: warning: implicit declaration of function 'free' is invalid in C99 [-Wimplicit-function-declaration]
1 warning generated.
/usr/bin/ld: /tmp/main-3866ce.o: in function `main':
main.c:(.text+0x20): undefined reference to `free'
</pre>
<p>The problem is that <code>main.c</code> has a transitive dependency on <code>stdlib.h</code>. The program compiled because <code>utils.h</code> included it. As soon as it was removed, the translation unit originating from <code>main.c</code> fails to compile. The solution is to make all source files self-reliant without transitive header dependencies.
<table>
<tr>
<td>
</td>
<td>
<pre>// b.h
#pragma once