Professional Documents
Culture Documents
6: Wrapping Up C (For Now) : 252-0061-00 V Systems Programming and Computer Architecture
6: Wrapping Up C (For Now) : 252-0061-00 V Systems Programming and Computer Architecture
gcc –S foo.c
.c,.h .i .s .o
gcc –c foo.c
See: http://gcc.gnu.org/onlinedocs/cpp/Swallowing-the-Semicolon.html
We'll see all this in more detail later when we look at Linking
Systems Programming 2019 Ch. 6: Wrapping up C 14
Modularity in C
• Module: self-contained piece of a larger program
• Consists of:
• Externally visible: The module's
• functions to be invoked
interface
• typedefs and perhaps global variables
• cpp macros
• Internal functions, types, global variables clients should not look at
… (declarations, macros)
#endif // __FILE_H_
$ ./a.out
a.out: assert_text.c:8: array_copy: Assertion `a != ((void *)0)' failed.
Aborted
$
Systems Programming 2019 Ch. 6: Wrapping up C 25
Assertions
• Almost a poor person’s contracts
• Checked at runtime, not compile time
• Can be compiled out (-DNDEBUG)
no runtime overhead in finished(!) code
• It’s a macro (why?)
Should not contain side-effects!
• Assertions are of no use to the user!
#include <assert.h>
#include <stdio.h>
...
int i,j;
int a[MAXROW][MAXCOL] int found=0;
for(i=0; i< MAXROW; i++) {
int i,j; for(j=0; j < MAXCOL; j++) {
for(i=0; i< MAXROW; i++) { Compare: if (a[i][j] == 0) {
for(j=0; j < MAXCOL; j++) { found=1;
if (a[i][j] == 0) { break;
goto found; }
} }
} if (found)
} break;
<do some processing when not found> }
found: if (found) {
<do some processing on i and j> <do processing on i and j>
} else {
<do processing when not found>
}
• But consider simply using return()
• Other languages have break(label)
Systems Programming 2019 Ch. 6: Wrapping up C 30
Cleanup conditions
Goto is used for recovery code
• General idea:
• Code performs a sequence of operations
• Any one can fail
• If one fails, all previous operations must be undone
• Canonical example:
• Malloc’ing a sequence of buffers for data
• If one fails, must free all previous generated buffers
• Code is often (not always) auto-generated
Cleanup
{
__be32 *p;
int error;
void second(void) {
printf("second\n");
longjmp(buf,1);
}
Output:
second void first(void) {
main second();
printf("first\n"); // does not print
}
int main() {
if ( ! setjmp(buf) ) {
first(); // when executed, setjmp returns 0
} else { // when longjmp jumps back, setjmp returns 1
printf("main\n"); // prints
}
return 0;
}
Systems Programming 2019 Ch. 6: Wrapping up C
(from wikipedia) 38
6.7: Coroutines
Coro_switchTo(A,B) Coro_switchTo(B,A)
long_jmp(B,1)
0
setjmp() setjmp()
0
long_jmp(A,1)
1 1