(no commit message)
[ikiwiki.git] / docs / developer / C_Development_Under_DragonFly_BSD-Volume_1_C_For_Beginners.mdwn
1 # C Development Under DragonFly BSD Volume 1: C For Beginners 
2
3 ## old title Volume 1: C For Beginners
4
5
6 [[!toc  levels=2]]
7
8
9
10
11 ## Prologue 
12
13
14 * Discuss a small bit about C's features, pros and cons, etc. 
15
16
17 * Tell a bit about its history, authors, etc. 
18
19
20 * Why is understanding C important? 
21
22
23 * Discuss its use in DragonFly 
24
25
26 * Why is DragonFly BSD a good programming environment? 
27
28
29
30 Contrary to what might be perceived of the C programming language by a beginner, the language is not large at all. In fact, C is one of the smaller programming languages, with a mere 32 keywords. 
31
32
33
34 Written singlehandedly in 1972 by AT&T Bell Laboratories' Dennis Ritchie, C has had almost thirty years to mature into what it is today. It is a general-purpose, low-level programming language which has, over the years, been used for myriad tasks. Many of the programs and utilities (and probably the better part of the operating systems) you've used have been written in C. 
35
36
37
38 ## Discussion of the C Language  
39
40
41
42 This chapter should be a breeze-through of the following chapters, touching on several key points, but mostly providing information for the sake of getting the reader oriented with the syntax, writing style, etc. 
43
44
45
46 ### Overview 
47
48
49
50 In this chapter, we will walk through the C language, touching on some of the more important features of the language. After reading this chapter, you should be superficially familiar with the [syntax](/C_Development_Under_DragonFly_BSD-Volume_7_Glossary_and_Tables_for_all_Volumes/#index1h1) of the C language as well as the aesthetical organization of source code within programs. 
51
52
53
54
55
56 ### Our First Program 
57
58
59
60 In the tradition of any programming book, we will begin our journey into the C programming language with a program which will output the words, "Hello, World!" onto our screen. In C, "Hello, World!" looks like this: 
61
62
63
64     
65
66     /* Includes */
67
68     #include <stdio.h>
69
70     
71
72     /* Main */
73
74     int
75
76     main(void)
77
78     {
79
80             printf("Hello, World!\n");
81
82             return (0);
83
84     }
85
86
87
88
89
90 While this is one of the most basic C programs that can be written, there are many things that can be learned from it. Let's take this program apart and discuss what each section of it does. 
91
92
93
94     
95
96     /* Includes */
97
98
99
100
101
102 The first line in this program is a [comment](/C_Book_Glossary). In C, comments are declared in between the symbol combinations `/*` and `*/`; they are not compiled and are only useful to inform persons reading the source code of what is happening in the code. We'll talk more about them in our next example. 
103
104
105
106     
107
108     #include <stdio.h>
109
110
111
112
113
114 Since C is such a small language, it's pretty unuseful by itself. DragonFly BSD provides an implementation of the [standard library](/C_Book_Glossary), which contains a number of useful functions. [Header Files](/C_Book_Glossary) contain definitions of functions, structures, and other interface portions of a program. In this case, we're telling the compiler to load the header file containing definitions for standard input and output routines. We use the file `stdio.h` because it provides the definition of the function `printf()`, which we use later in the program. 
115
116
117
118     
119
120     /* Main */
121
122
123
124
125
126 Here, we see a comment implying that we're looking at the main section of the program. This is the case; all C programs begin with the `main` function, which is defined directly after this comment. 
127
128
129
130     
131
132     int
133
134     main(void)
135
136
137
138
139
140 This is the definition of the `main` function, and there are several things that we should touch on before taking a look into the body of the function. First of all, function declarations all follow a standard pattern: 
141
142
143
144     
145
146     modifier type functionname(parameterlist);
147
148
149
150
151
152 The [modifier](/C_Book_Glossary) is an optional keyword which specifies (modifies) the function type. [type](/C_Book_Glossary) refers to the variable type that should be returned by the function. `Functionname` is any valid C language variable name. The list of parameters that should be passed to the function are given in a comma-delimited format in the `parameterlist`. 
153
154
155
156 Using the above information, we can assume that the modifier is missing, the type of the function is `int` (this means "integer"), its name is `main` and it accepts an argument of type `void`. All these assumptions are correct except the last; a function accepting an argument of type `void` actually signifies a function with no arguments. Thus, we would read our definition of the main function, "Main is a function returning an integer type and accepting no (void) arguments." 
157
158
159
160     
161
162     {
163
164             printf("Hello, World!\n");
165
166             return (0);
167
168     }
169
170
171
172
173
174 This is the body of the main function. All function bodies must be contained between a matching set of open and closed curly braces ({ and }). 
175
176
177
178     
179
180             printf("Hello, World!\n");
181
182
183
184
185
186 The function printf is provided in the standard library, and is used to print formatted output to the standard output (usually a monitor, console, or terminal session). In this case, we're asking it to print the [string](/C_Book_Glossary), "Hello, World!\n" to the standard output. If you were to actually run this program, you would notice the following output: 
187
188
189
190     
191
192     $ ./hello
193
194     Hello, World!
195
196     $
197
198
199
200
201
202 What happened to the `\n? \n` is an escape string signifying a newline. Since it is illegal to put line breaks inside of C strings, we must signify that we would like to insert one somehow. `\n` is the solution. 
203
204
205
206     
207
208     return (0);
209
210
211
212
213
214 Since we defined the `main` function as a function returning an integer, we must actually do so. The `return` keyword signifies that the function should terminate at its current point of execution and give the returned value to its calling function. 
215
216
217
218 You may be wondering where this value is returned - after all, the `main` function signifies the beginning of the program, so why do we need to return something from it? There's nothing calling our program, is there? In fact, there is, but this is outside the scope of this section. This will be discussed later in the book, but if you absolutely can't wait to find out, please see the Glossary entry on the [return](/C_Book_Glossary) keyword. 
219
220
221
222 So, we're done with our overview of the source code. Now how do we run it? 
223
224
225
226 To be able to run the program, we must first compile it. Compiling C programs is quite simple in DragonFly BSD; the GNU Compiler Collection (GCC) is included in DragonFly BSD and it is used to compile C programs which can be distributed among and run on any DragonFly BSD system. To compile our "Hello, World!" program above, simply save the text of the program in a file called `hello.c`. Run the following command to compile the source code file: 
227
228
229
230     
231
232     $ cc hello.c -o hello
233
234
235
236
237
238 When the program is compiled, you can test it with: 
239
240
241
242     
243
244     $ ./hello
245
246
247
248
249
250 This will produce the output we saw above: 
251
252
253
254     
255
256     Hello, World!
257
258     $
259
260
261
262
263
264 Most of the programs discussed in this book can be compiled in this same manner. 
265
266
267
268 ## Simple Concepts - Variables, Operators, Types and Expressions 
269
270
271
272 In most programming languages, understanding how to program in that language requires the understanding of some quite simple concepts: variables, operators, types and expressions. What do all of these terms mean? 
273
274
275
276  **Variables**  are essentially mnemonics for data; this definition applies to C as well. Variables are used in C to refer to data. The term "variable" itself implies that the data contained in the mnemonic may vary. This is not always the case in C and, in this sense, the term "variable" may seem a misnomer. 
277
278
279
280  **Operators**  refer to popular mathematical operators. Operators are symbols that represent operations that should be applied to or carried out upon a variable. The symbol "+" in C is thus the addition operator, "-" is the subtraction operator, and so forth. 
281
282
283
284  **Types**  refer to the sort of data that a variable can contain. In C, there are several data types, including integral, decimal, character and grouped types (called structures). 
285
286
287
288 An  **expression**  is the grouping of the above (variables, operators and types) to express a certain process. 
289
290
291
292 ### Variables and Types 
293
294
295
296 Variables in C are used for many different purposes: to keep track of iterations in a loop, to store data from a file, to store input from a user, and much more. However, different types of variables might be used for each one of the previous examples. Since variables and types are so closely related, we will discuss them hand-in-hand in this section. 
297
298
299
300 C is what is called a `typed`  language. This means that variables must be given a type when they are defined in a program. As explained earlier, variables in C can be of several data types. The following types are supported in C: 
301
302
303
304
305 * `int` -- `int` refers to an integral number (an integer). An integer is any non-fractional number (..., -1, 0, 1, ...). 
306
307
308 * `float` -- The `float` type refers to a floating point number; that is, a number with a decimal point. 
309
310
311 * `double` -- `double` means double precision floating point: it is another way to represent fractional numbers, but has better precision than the float type. 
312
313
314 * `char` -- Characters are represented with the `char` type. This type is really a special case for denoting that the number should be mapped to represent a single ASCII character. 
315
316
317 * `void` -- Variables of this type are unable to store information; they are void of type. 
318
319
320
321 In addition to these types, there are a few other special data types in C; these types will be discussed later in the book since the application of these types is usually reserved for semi-advanced work. 
322
323 `struct` -- Structures, denoted by their C type `struct`, are variables that contain multiple variable types. One might use a structure to store information about an employee (such as their name, address, phone number, salary, etc). 
324
325 `union` -- Unions are similar to structures in that they can contain multiple types, but different in that can only store one type at a time. Unions are useful to store information with a variable type. 
326
327 `enum` -- `enum`, short for "enumeration," is used to declare and initialize a sequence of integers. 
328
329
330
331
332
333 ## Controlling the Flow of Programs: Control Structures and Functions 
334
335
336
337 ### Control Structures 
338
339
340
341 Control Structures are statements which are used to repeatedly or conditionally execute part of the program. 
342
343
344
345 #### Conditional execution 
346
347
348
349 Conditional execution is accomplished with the if statement. If the expression following it evaluates to nonzero the statements following if are executed. If the expression's value is zero then all statements following the else are executed (if an else exists). 
350
351
352
353 ###### Format 
354
355
356
357     
358
359     if (expression) {
360
361             /* These statements will execute */
362
363             ;
364
365     } else {
366
367             /* These other statements will execute */
368
369             ;
370
371     }
372
373
374
375
376
377 ###### Example 
378
379
380
381     
382
383     if (i # 128) {
384
385             printf("The variable i has the value 128!\n");
386
387     } else {
388
389             printf("i isn't 128, sorry!\n");
390
391     }
392
393
394
395
396
397 ##### Loops 
398
399
400
401 `do`, `for` and `while` are used to execute parts of the program multiple times. 
402
403
404
405 ##### do 
406
407
408
409 ##### for 
410
411
412
413 The `for` loop is commonly used when you know the number of times to repeat your statements. It has three clauses: initial, expression, and increment. The initial clause is only executed when the `for` loop is first entered. After that for each iteration of the loop first the expression clause is evaluated. If the result of the expression is nonzero the statements are executed. If it is zero, the loop is finished. If the value of the expression clause was nonzero the increment clause is executed after statement execution. Each clause can be ommitted. 
414
415
416
417 ###### Format 
418
419
420
421     
422
423     for (initial; expression; increment) {
424
425             /* Statements to be executed */
426
427             ;
428
429     }
430
431
432
433
434
435 The following `for` loop will count from 0 to 9. 
436
437 ###### Example 
438
439
440
441     
442
443     int i;
444
445     
446
447     for (i = 0; i < 10; i++) { 
448
449             printf("This is the %d time this loop has fired\n", i); 
450
451     }
452
453
454
455
456
457 ##### while 
458
459
460
461 The `while` loop is used when the number of times statements should be executed depends on a condition. The `while` loop is executed as long as the expression evaluates to nonzero. 
462
463
464
465 The `while` loop checks the condition  **before**  it executes any statements, see `do while` loop for condition check  **after**  the first statement execution. 
466
467 ###### Format 
468
469
470
471     
472
473     while (expression) {
474
475              /* Statements to execute */
476
477              ;
478
479     }
480
481
482
483 ###### Example 
484
485
486
487     
488
489     while (finished != true) {
490
491             /* code goes here */
492
493     }
494
495
496
497
498
499 ##### do while 
500
501
502
503     
504
505     do {
506
507              /* Statements to execute */
508
509              ;
510
511     } while (again # true);
512
513
514
515
516
517
518 * Small overview of (simple) frequently used functions from the standard library. 
519
520
521 * When should you used typedef, macros, etc. 
522
523
524 * More... 
525
526
527 * Overview, exercises and examples 
528
529
530
531 ### Functions 
532
533
534
535
536
537
538
539 ## Arrays and Pointers 
540
541
542
543 Arrays are arrangements of variables of the same [type](/C_Book_Glossary). 
544
545
546
547 A good example of a simple array is a word, where each character of this word is a single variable of the type `char`, with it's own fixed place.
548
549 For example the word `Dragon` is an array of chars, with a length of six. We can create it as follows:
550
551
552
553 `char my_array_name[6];`
554
555
556
557 The number inside the brackets indicates the amount of variables the array is made up of. Each single character has it's own place and thus each place has an address whereby we can reach it. `D` is at the first position in the word `Dragon`, and because most programming languages start counting at zero, `D` can be found at `my_array_name[0]`, whereas `r` is stored at `my_array_name[1]`, and the last character of `Dragon`, `n` resides at `my_array_name[5]`. 
558
559
560
561 Arrays are even more flexible than that. We can add more dimensions to it, so like in a graph with an abscissa and an ordinate, every X value should have corresponding Y entry.
562
563
564
565 XXX: I haven't been able to found the graphic named "a graph with two dimensions" that should
566
567 be here. You can't download images from the google cache :(
568
569
570
571 So if we want to store information in pairs or more, of the same data type, we add a dimension while creating the array, thus having a two dimensional array:
572
573
574
575     
576
577     int my_array_name[3][2];
578
579
580
581
582
583 So `[3][2]` means, the first dimension of our array of ints, has a length of three and each of those three are infact two values in the second dimension. If the first entry of a pair represents the abscissa and the second the ordinate, our graph above could be described as follows. 
584
585
586
587 XXX: Here should be a table with different colors that i don't know how to do
588
589
590
591 my_array_name[0][0]='0'; 
592
593 my_array_name[0][1]='0'; 
594
595 my_array_name[1][0]='1'; 
596
597 my_array_name[1][1]='2'; 
598
599 my_array_name[2][0]='2'; 
600
601 my_array_name[2][1]='1'; 
602
603
604
605                 0-0 holds 0     1-0 holds 1     2-0 holds 2 
606
607 0-1 holds 0     1-1 holds 2     2-1 holds 1 
608
609
610
611
612
613
614
615 By adding more `deepness` to the second dimension e.g. `int array_name[3][4]`, it is possible to add more attributes to a group of data, an Z-axis value for the graph or thickness at a certain point. You may already have noticed that, logically, `int array_name[n]` equals to `int array_name[n][0]` or `int array_name[n][0][0]`. Because we always address the first value of the next empty dimension. 
616
617
618
619 ### more on pointers later 
620
621
622
623 ## Allocating Memory 
624
625
626
627 I'd actually like to discuss how memory is handled here and provide a small, simple, secure allocator that I've written. 
628
629
630
631
632
633 ## Structures 
634
635
636
637 It's late in the book to go deep into them, but we can do some really neat stuff with them later. 
638
639
640
641
642
643 ## The Standard Library 
644
645
646
647
648
649 ## POSIX and C99 Features 
650
651
652
653 Discuss integer types, functions, and portability with C programs following the C99 and POSIX standards. 
654
655
656
657
658
659 ## The Programming Process 
660
661
662
663
664 * Discuss the theory of writing programs 
665
666
667 * Partition large programs into libraries. 
668
669
670 * How to write Makefiles for programs 
671
672
673 * DragonFly BSD's /usr/share/mk/* and how it makes everything easier 
674
675
676 * Compiling many files into single binaries 
677
678
679 * Building static libraries 
680
681
682 * Building dynamic libraries 
683
684
685
686
687
688
689
690 ### Section Notes 
691
692
693
694 ## Unorganized Information 
695
696
697
698 When learning C, especially when coming from other programming languages, it is important to fully understand the fundamentals of the language. In this chapter, we will discuss the fundamentals of the C programming language, explore example programs, and discuss some basic, DragonFly BSD-specific features. 
699
700
701
702
703
704 ### Data Types 
705
706
707 * C has a few simple data types 
708
709
710 * `int` -- A non-factional number (integer), e.g. 123456 
711
712
713 * `float` -- A number with a decimal point, e.g. 3.14 
714
715
716 * `double` -- Another number with a decimal point. While it has better precision than `float`, it does use more memory, e.g. 3.14159 
717
718
719 * `char` -- A special case for integers that represent a single ASCII character 
720
721
722 * `void` -- A special type used to denote nothing 
723
724
725
726 C is what is called a `typed` language. This means that variables must be given a type when they are defined in a program. For more information about typed languages, please see the Section Notes. C provides several types which you must use when defining your variables. Let's take a look at an example: 
727
728
729
730     
731
732     /* Includes */
733
734     #include <stdio.h>
735
736     
737
738     /* Main */
739
740     int
741
742     main(void)
743
744     {
745
746             int a;
747
748     
749
750             a = 1;
751
752             printf("a is %d\n", a);
753
754             return 0;
755
756     }
757
758
759
760
761
762
763
764 ### Arrays 
765
766
767
768 An array is a collection of items of a certain type. 
769
770
771
772
773
774 ### Structures 
775
776
777
778 #### This section needs to be moved into a separate chapter on structures 
779
780
781
782 Another "type" available in C is the structure. C also allows its user to create their own types using the struct keyword. Below is an example of a user-defined structure: 
783
784
785
786     
787
788     struct {
789
790             char FirstName[50];
791
792             char MiddleName[50];
793
794             char LastName[50];
795
796     } person;
797
798
799
800
801
802 The above example has created a structure called person that consists of a FirstName, MiddleName, and a LastName. Each name is limited to 50 ASCII characters. 
803
804
805
806 #### Section Notes 
807
808
809
810 Should we go into more depth about language types? It's a quite disputed field and people don't generally agree on the absolute definitions of: "strongly typed," "weakly typed," "statically typed," or "dynamically typed." I don't want to start an introduction to the language with confusing definitions about what 
811
812
813
814 TODO: deal with the dangling `else` problem
815
816
817
818 TODO: explain the `do` statement 
819
820
821
822
823
824 ### Memory and C 
825
826
827 * Briefly and superficially discuss how memory works as seen by a program. (It is okay to discuss `sbrk()` & friends) 
828
829
830 * `mmap()` When is it really useful. Matt wrote something about it a while back. 
831
832
833 * Why is working with memory important? 
834
835
836 * Terminology: pointer to type, (de)referencing, etc 
837
838
839 * Discuss simple pointer usage 
840
841
842 * Strings 
843
844
845 * Overview, exercises and examples 
846
847
848
849
850
851 #### Section Notes 
852
853
854
855
856
857 ### Stuff 
858
859
860
861 that should go somewhere but needs to find a good place: 
862
863
864
865 ### Syntax 
866
867
868
869 The C syntax is a combination of [keywords](/C_Book_Glossary), [operators](/C_Book_Glossary), variables and symbols to determine program content and flow. 
870
871
872
873 ### Header files 
874
875
876
877 In general they do not actually implement functions. As these files implement interfaces, they are generally used for two purposes: 
878
879
880 * To provide interfaces to a library (the standard C library, for example), and 
881
882
883 * To allow for proper abstraction in projects by providing interfaces which can be used between source files. 
884
885
886
887 Header files are imported into C source files using the [preprocessor directive](PreprocessorDirective) `#include`. 
888
889
890
891 ### Comments 
892
893
894
895 Comments can span multiple lines and can contain any text (other than */), however, they cannot be nested. 
896
897
898
899 Comments are very useful inside code and are used in DragonFly BSD (and in most C programs in general) frequently for any of the following reasons: 
900
901
902 * To give information about any license(s) under which the code is available. 
903
904
905 * To discuss the purpose of a function. 
906
907
908 * To give information about perhaps otherwise difficult to understand pieces of code. 
909
910
911
912 When programming for DragonFly BSD, comments are encouraged. It is in general good practice to add comments describing what happens in a function before its declaration, rather than in the body of that function. That said, comments should absolutely not be overused. When overused, comments can make code unreadable. 
913
914
915
916 Examples of different kinds of comments include: 
917
918
919
920     
921
922     /* This is a comment on a single line. */
923
924     /*
925     
926      * This is how comments that span multiple lines should be formatted,
927     
928      * as detailed by the style(9) manual page.
929     
930      */
931
932     /*
933     
934      * /* This comment is invalid because it is nested. This will cause a
935     
936      *  * compiler error on the line that closes the ***first comment.
937     
938      *  */
939     
940      */
941
942
943
944
945
946
947
948 ### Functions 
949
950
951 * Function declaration 
952
953
954
955 A function is declared using the following syntax: 
956
957
958
959 Some valid function definitions are: 
960
961
962
963     
964
965     extern int
966
967     ext_function(char *, char *, unsigned long);
968
969     char *
970
971     function_b(void);
972
973     int
974
975     printf(const char *format, ...);
976
977
978
979
980
981 Don't worry if you don't understand what each definition implies; we will cover this in more detail later. One function defintion that is important to understand at this point is the `main` function: it is called at the beginning of every program and is thus necessary for every C program. The `main` function will always take one of the following forms: 
982
983     
984
985     int
986
987     main(void)
988
989     {
990
991             :
992
993             :
994
995             :
996
997     }
998
999
1000
1001
1002
1003  **- or -** 
1004
1005     
1006
1007     int
1008
1009     main(int argc, char **argv)
1010
1011     {
1012
1013             :
1014
1015             :
1016
1017             :
1018
1019     }
1020
1021
1022
1023
1024
1025  **TODO**  Add chapter about the preprocessor
1026