You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: appendices/c-preprocessor.md
+15-6Lines changed: 15 additions & 6 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -1,16 +1,25 @@
1
+
```{index} C Preprocessor
2
+
```
1
3
# The C preprocessor
2
-
```{index} C Preprocessor ```
4
+
3
5
4
6
This page briefly describes the C preprocessor which is by default run on every file before compilation. The preprocessor modifies the text of the code which is seen by the actual compiler based on its own collection of commands, which are known as preprocessor directives. These commands can add, remove or change code in a number of ways and together act to simplify the process of making code run in multiple configurations or on multiple systems.
5
7
6
8
## Preprocessor directives.
7
9
8
10
You have already seen some common preprocessor directives while working with :doc:`header_files`. The `#include` directive is one of the most commonly used and most visible C preprocessor directives, which "under the hood" directs the preprocessor to copy the entire (processed) text of another file into the file being worked on. Similarly, the `#pragma once` or `#if ndef ...` patterns are also directives, either explicitly commanding the preprocesser to only work on the file once, or generating the same effect using a preprocessor variable. The full(ish) list of possible standard directives is
9
11
10
-
|#define |#elif|#else|#endif|
11
-
|#error |#if |#ifdef|#ifndef|
12
-
|#import |#include|#line|#pragma
13
-
|#undef|#warning|||
12
+
13
+
| Control Structures | Logging Controls | Others |
14
+
|--------------------|---------|-------|
15
+
| #if | #error | #define |
16
+
| #elif| #warning |#pragma|
17
+
| #else|| #include|
18
+
| #ifdef || #undef |
19
+
| #ifndef || #line |
20
+
| #endif |||
21
+
22
+
14
23
15
24
## Defining preprocessor macros
16
25
@@ -20,7 +29,7 @@ Beside `#include`, which appears in many C/C++ files, the conditional directives
20
29
21
30
Any if-like block can optionally have an `#else` block attached to if. As with Python or C, the `#else` block matters (i.e. is passed to the compiler) if the first expression doesn't evaluate true, in which case it is compiled. These if blocks can be nested providing every block is terminated correctly.
22
31
23
-
As a concrete example, consider the code block
32
+
As a concrete example, consider the following code block:
Copy file name to clipboardExpand all lines: appendices/keywords.rst
+61-4Lines changed: 61 additions & 4 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -10,12 +10,15 @@ Storage keywords
10
10
11
11
.. glossary::
12
12
13
-
auto
13
+
auto (C version)
14
14
Declare variable which is automatically cleaned up when coming out of scope and is stored locally (i.e. exactly the default behaviour). *C++ behaviour is different*
15
+
15
16
register
16
17
*Suggests* to the compiler that the variable should be stored in a register rather than RAM. This allows fast access, but limits behaviour (e.g. it cannot be used with `&`).
18
+
17
19
static
18
20
Declare a variable which exists for the lifetime of the program.
21
+
19
22
extern
20
23
Declare a variable name which has memory storage assigned elsewhere.
21
24
@@ -26,34 +29,49 @@ Datatype keywords
26
29
27
30
char
28
31
One byte data type, often used to store text with ASCII encoding.
32
+
29
33
const
30
34
Qualifier indicating a variable will not change its value while it is in scope.
35
+
31
36
double
32
37
A double precision (i.e. usually 64 bit, 8 byte) floating point number. Directly equivalent to the Python `float` or `numpy` `float64`.
38
+
33
39
enum
34
40
Declare a list of names which are mapped to integer values (automatically, if manual values aren't given).
41
+
35
42
float
36
43
A single precision (i.e. usually 32 bit, 4 byte) floating point number. Equivalent to the `numpy` `float32`.
44
+
37
45
int
38
46
An integer (usually 4 bytes on modern systems). Equivalent to `numpy` `int32`.
47
+
39
48
long
40
49
By itself declares a long integer (usually 8 bytes on modern systems). Equivalent to `numpy` `int64`. Can also be used as a qualifier with `double` for 10 byte floating point number.
50
+
41
51
restrict
52
+
Qualifier which indicates that a pointer is the only pointer which can access the memory it points to. This allows the compiler to make optimisations which would otherwise be unsafe.
42
53
43
54
short
44
55
A 2 byte integer. Equivalent to `numpy` `int16`.
56
+
45
57
signed
46
58
Qualifiers which declares integers to be signed (i.e take both positive and negative numbers). Default behaviour.
59
+
47
60
struct
48
61
Declares a combined data structure containing other datatypes as separate members.
62
+
49
63
typedef
50
64
Declare an alias for a (possibly qualified) datatype.
65
+
51
66
union
52
67
Declares a combined data type containing other data types all sharing the same memory.
68
+
53
69
unsigned
54
70
Qualifier which declares integers to be unsigned (i.e. positive, ranging from 0 to the largest number which fits in the memory space).
71
+
55
72
void
56
73
Data type representing no specific sort of value.
74
+
57
75
volatile
58
76
Qualifier indicating that a value is liable to change at any time. Ensures the compiler will execute commands using the variable in the order they are written.
59
77
@@ -64,28 +82,40 @@ Control keywords
64
82
65
83
break
66
84
Exit the innermost loop (in the current scope) currently executing.
85
+
67
86
case
68
87
Declare one option in a `switch` statement.
88
+
69
89
continue
70
90
Skip to the next iteration of a loop.
91
+
71
92
default
72
93
Declare a default option for a `switch` statement.
94
+
73
95
do
74
96
Start a `do ... while` loop block.
97
+
75
98
else
76
99
Declare alternative behaviour for an `if` block, executed when the `if` statement is not true.
100
+
77
101
for
78
102
Declare a `for` loop.
103
+
79
104
goto
80
105
Jump to another labelled section of code (Use with great care).
106
+
81
107
if
82
108
Declare a conditional code block, which runs only when the test expression is true.
109
+
83
110
inline
84
111
Function specfier which *suggests* to a compiler that it places the relevant code directly in place, avoiding the overhead of a function call.
112
+
85
113
return
86
-
Exit a function and pass any `return` value to the calling routine.
114
+
Exit a function and pass any `return` value (which must be convertable to the specified data type) to the calling routine.
115
+
87
116
switch
88
117
Declare a `switch` block with multiple cases.
118
+
89
119
while
90
120
Either declare a `while` loop, or terminate a `do .. while` block.
91
121
@@ -115,29 +145,56 @@ Important keywords
115
145
116
146
.. glossary::
117
147
118
-
auto
148
+
auto (C++ version)
119
149
Declare a variable which automatically identifies its data type based on the context in which it is used. *Different from C behaviour*.
150
+
120
151
bool
121
152
Boolean datatype.
153
+
122
154
catch
123
155
Associate exception handlers with a `try` statement block, somewhat similar to Python.
156
+
124
157
class
125
158
Object oriented combined structure holding both data and functions, which usually act upon that data.
159
+
126
160
delete
161
+
Delete a variable or object, and return the memory it was using to the operating system.
162
+
127
163
false
128
-
Boolean data indicating a false value.
164
+
Boolean data indicating a false value. Opposite of `true`, and equivalent to `0`.
165
+
129
166
friend
130
167
Specifier indicating a function/class can access private or protected data stored in the declaring class.
168
+
131
169
operator
132
170
Declares an overloading of an operator for a user declared data type (i.e. lets the programmer use it with standard C++ operators such as `+` or `<<`).
171
+
133
172
namespace
173
+
Declare a namespace, which is a way of grouping together related functions and classes (which acts a bit like a Python package/module).
174
+
134
175
new
176
+
Allocate new memory for a variable, array or object, and return a pointer to it.
177
+
178
+
nullptr
179
+
A canonical pointer value (i.e. a pointer which points to nothing). Useful for initialising pointers or checking if a pointer is valid.
180
+
135
181
private
182
+
Declare a class member which can only be accessed by functions within the class itself (i.e. not by functions outside the class which use an object of that class). Opposite of `public`.
183
+
136
184
public
185
+
Declare a class member which can be freely accessed by functions outside the class which use an object of that class. Opposite of `private`.
186
+
137
187
this
188
+
Pointer to the current object, which is passed implicitly to member functions. Useful for accessing other members of the same object if they have the same name as a local variable (e.g. a method argument).
189
+
138
190
throw
191
+
Throw an exception, which can be caught by a `catch` statement. (Similar to Python `raise`).
192
+
139
193
true
194
+
Boolean data indicating a true value. Opposite of `false`, and equivalent to `1`.
195
+
140
196
virtual
197
+
Declare a virtual function, which can be overridden by a function of the same name in a derived class. Indicates that the function should be called based on the type of the object, rather than the type of the pointer to the object.
Copy file name to clipboardExpand all lines: intro.md
+5-1Lines changed: 5 additions & 1 deletion
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -18,5 +18,9 @@ Python is what is known as an interpreted language. To run code, you point a sin
18
18
19
19
Python is also a garbage-collected language. It cleans up (eventually) all the memory you use to hold variables in your programs, once it realises you're no longer interested in them. C-like languages give you, as a programmer, more power & control on where in your computer memory things live, and how long they stay around for. In return, it is often the programmer's job to clean up once you have finished
20
20
21
-
## Next Section - Getting Started
21
+
## Summary
22
+
23
+
In this section we have introduced the C & C++ programming languages, and given a brief motivation for why we might want to use them in preference to another language such as Python.
24
+
25
+
In the next section we will look at how to compile and run C & C++ code on your own computer.
Copy file name to clipboardExpand all lines: part_one/01_running.md
+11-7Lines changed: 11 additions & 7 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -39,7 +39,7 @@ Here `g++` is the name of the linux GNU C++ compiler, the `-o` option specifies
39
39
## Compiling natively
40
40
41
41
### Windows: Visual Studio
42
-
```{index} compiling:windows
42
+
```{index} compiling:windows native
43
43
```
44
44
45
45
For Windows users only, you can obtain the Microsoft C/C++ compiler by downloading the Visual Studio community package [here](https://visualstudio.microsoft.com/vs/community/). Visual Studio is a sister package to Visual Studio Code, which combines build tools for several programming languages along with an Integrating Development Environment (IDE) to code them in.
@@ -62,17 +62,17 @@ Most Mac users on th course will already have Homebrew installed, but for those
62
62
brew install gcc
63
63
```
64
64
65
-
will install a recent version of `gcc` as well as placing it in your standard path. Once installed, (and having openned a new terminal) you can confirm that things work by running the following command in a terminal
65
+
will install a recent version of `gcc`(version 13 as of early December 2023) as well as placing it in your standard path. Once installed, (and having openned a new terminal) you can confirm that things work by running the following command in a terminal
66
66
67
67
```
68
-
gcc-12 --version
68
+
gcc-13 --version
69
69
```
70
70
71
71
You should see a response something like
72
72
73
73
```
74
-
gcc-12 (Homebrew GCC 12.2.0_1) 12.2.0
75
-
Copyright (C) 2022 Free Software Foundation, Inc.
74
+
gcc-12 (Homebrew GCC 13.2.0) 13.2.0
75
+
Copyright (C) 2023 Free Software Foundation, Inc.
76
76
This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
77
77
```
78
78
@@ -83,7 +83,9 @@ g++-12 -o hello hello.cpp
83
83
./hello
84
84
```
85
85
86
-
Here `g++-12` is the name of your new GNU C++ compiler, the `-o` option specifies the name of the output file (the default is `a.out`) and we must list the `.cpp` source file to compile into it. The second line then runs our new executable.
86
+
Here `g++-13` is the name of your new GNU C++ compiler (version number 13), the `-o` option specifies the name of the output file (the default is `a.out`) and we must list the `.cpp` source file to compile into it. The second line then runs our new executable file which we have just compiled.
87
+
88
+
Remember, we only need to compile once, and then we can run the executable as many times as we like. If we make any changes to the source code, we must recompile before we can run the new version and see the results.
87
89
88
90
#### Xcode
89
91
@@ -115,7 +117,9 @@ c++ -o hello hello.cpp
115
117
Here `c++` is the name of your C++ compiler, the `-o` option specifies the name of the output file (the default is `a.out`) and we must list the `.cpp` source file to compile into it. The second line then runs our new executable.
116
118
117
119
118
-
### Linux
120
+
### Linux/WSL: `gcc` or `clang`
121
+
```{index} compiling:linux
122
+
```
119
123
120
124
Linux users are likely to find C compilers are either installed by default on most desktop distributions, or readily installable via the system package manager. Given the wide range of distributions in use, we can't hope to cover all of them, but for some of the more popular ones:
Copy file name to clipboardExpand all lines: part_one/02_hello_world.md
+13-11Lines changed: 13 additions & 11 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -1,8 +1,8 @@
1
1
# Hello World!
2
2
3
-
## Preface
3
+
## Introduction
4
4
5
-
Now that you have access to a working compiler, we'll move on to giving you some practical code to compile. A common first program for people to code in a new programming language is to write just enough code to print the phrase "Hello World!" to the screen (or other output device) and then exit.
5
+
Now that you hopefully have access to a working compiler, and a place to writewe'll move on to giving you some practical code to compile. A common first program for people to code in a new programming language is to write just enough code to print the phrase "Hello World!" to the screen (or other output device) and then exit.
6
6
7
7
The popularity of this tradition actually dates back to the beginnings of the C programming language in 1978 and the book "The C Programming Language" by Brian Kernighan and Dennis Ritchie.
8
8
@@ -32,11 +32,11 @@ _hello.c_:
32
32
}
33
33
```
34
34
35
-
Unlike Python, we need to use a function from outside the core language (in this case the function `printf` from the standard library `stdio`) in order to print our message to screen. At the compilation stage we do this with command `#include` (a C preprocessor directive), which in practice works somewhat similarly to the `import` statement in Python by pulling other code into our work.
35
+
Unlike Python, we need to use a function from outside the core language, in this case the function `printf` from the standard library `stdio`, in order to print our message to screen. At the compilation stage we do this with command `#include`, a C preprocessor directive, which in practice works very similarly to the `import` statement in Python by pulling other code into our work.
36
36
37
-
Where Python runs through commands beginning at the top of a script file, in `C` programs (at least, those printing to screen in the terminal) start at the beginning of the special `main` function. This function usually returns an integer, where `0` is taken to mean that things worked successfully, while other values are taken as a sign that something went wrong.
37
+
Where Python runs through commands beginning at the top of a script file, in `C` programs (at least, those printing to screen in the terminal) start at the beginning of the special `main` function. This function usually returns an integer, where `0` is taken to mean that things worked successfully, while other values are generally taken as a sign that something went wrong.
38
38
39
-
Finally, in C/C++ we **must** use the double quotes `"` to indicate a string (the `'` character won't work), and since the `printf` function doesn't end lines automatically, we must do it ourselves using the special end-of-line `\n` character.
39
+
Finally, in C/C++ we **must** use the double quotes `"` to indicate a string (the `'` character won't work, and is only used with single characters), and since the `printf` function doesn't end lines automatically, we must do it ourselves using the special end-of-line `\n` "escape" character.
40
40
41
41
## Hello World in C++
42
42
@@ -52,17 +52,19 @@ _hello.cpp_:
52
52
}
53
53
```
54
54
55
-
You'll see that in this case, the code looks very similar to the C example. In fact, most C code is valid C++ code (possibly with a few small changes). The only thing that looks different is that rather than using a function like `printf` we are using the special `<<` operator (i.e. a token which works a bit like `+` or `-`) to send our message to `std::cout`, an "output stream" which in this case represents the screen.
55
+
You'll see that in this case, the code looks very similar to the C example. In fact, most C code is valid C++ code (possibly with a few small changes). The only thing that looks different is that rather than using a function like `printf` we are using the special `<<` operator (i.e. a token which works a bit like `+` or `-`) to send our message to `std::cout`, an "output stream" which in this case represents printing to the screen.
56
56
57
-
## Key differences from Python
57
+
## Some key differences from Python
58
58
59
-
1. Whitespace doesn't matter (although it still makes things easier to read when nicely formatted).
60
-
2.Statements*must* end with a `;`.
61
-
3. The code starts in the `main` function.
62
-
4. Functions and variables have a fixed data type.
59
+
1. Whitespace doesn't matter (although it still makes things easier to read when code is nicely formatted).
60
+
2.Individual statements*must* end with a `;`.
61
+
3. The code starts running at the top of the `main` function. There can only be one `main` in a given programme.
62
+
4. Functions (and variables) have a fixed data type associated with them.
63
63
64
64
65
65
## Exercise: Run the Hello World programs
66
+
```{index} Exercises: Hello World
67
+
```
66
68
67
69
Run the three different programs in Python, C and C++. You already know how to run Python scripts. You can look back to the previous section to see how to run C & C++ codes.
0 commit comments