Diese Präsentation wurde erfolgreich gemeldet.
Wir verwenden Ihre LinkedIn Profilangaben und Informationen zu Ihren Aktivitäten, um Anzeigen zu personalisieren und Ihnen relevantere Inhalte anzuzeigen. Sie können Ihre Anzeigeneinstellungen jederzeit ändern.
Not Your Fathers C
C Application Development In 2016
Introduction
About Me
● Living in Leipzig
● five years of exploring ways to write high
level C
● C and me is a „convenienc...
Introduction
Leipzig Softwerkskammer
● Software Craftsmanship Community in
Leipzig
● Once a month
● Mix of coding and beer...
Introduction
My C Scope
● Application development in a legacy
system
● No embedded software
● I am not a kernel hacker
Introduction
Why Still C
● Legacy Code
● Embedded systems
● Speed
● Direct Memory Control (Garbage Collection
can be slow!)
A Punk Rock Language
[1]
A Punk Rock Language
Essay in PragProg Magazine
March 2011
[2]
A Punk Rock Language
1978
● Book release and first peak of Punk Rock
[4][3]
A Punk Rock Language
Three Chords Is Enough To
Form A Band
[5]
A Punk Rock Language
Three Basic Data Types In C
[6]
A Punk Rock Language
The Craftsman's Question
C is quirky, flawed, and an enormous
success.. (Dennis Ritchie On C)
[7]
How...
Structure
Structure
“On Information Hiding”
● „On the criteria to be used in decomposing
systems into modules”, CACM, Dec., 1972
by ...
Structure
A C Module
● A *.c file is called a “module”
● Should contain related functions and data
● How to design related...
Structure
What Is A Class
● A bunch of functions working on (mainly)
the same variables. (Uncle Bob)
● That's exactly what...
Structure
Main OO Structure Elements
● Classes – defines an object
● Methods – actions on the object's data
● Packages – o...
Structure
A Python Example
from long.package.path.my_class import MyClass
...
my_instance = MyClass()
print(my_instance.sa...
Structure
Objects in C
● Only function names in global name space
● We need to use a naming convention for
structuring:
– ...
Structure
Naming Example
● The Module name: MyClass.c
● Functions inside:
– The constructor: MyClass_create()
– A method: ...
Structure
Example Ported To C
#include "MyClass.h"
...
MyClass *my_instance = MyClass_create();
printf("%sn", MyClass_sayH...
Structure
Objects in C
● C can give you Object Orientation –
Without Inheritance
● It's no real OO – I just call it „Objec...
Structure
Objects In C - My Rules
● treat a C module as a class
● all public functions of that file are the methods of
the...
Structure
No Hard Rules
● A module can be designed as an object – but
it doesn't have to – simply related functions
are st...
Structure
Pebble Smart Watch
● Smart watch which started as crowd
funding campaign
[8]
Structure
„Hello Pebble“
Window *window;
TextLayer *text_layer;
void init() {
window = window_create();
text_layer = text_...
Abstraction
Abstraction
An Old Idea
Taken from „The Structure And Interpretation Of
Computer Programs“, 2nd Edition, MIT Press, 1996
Abstraction
The Standards
● ANSI standard (Strings, Math, Memory)
● Is enhanced by the Posix Standard
(Sockets, File descr...
Abstraction
What I Expect
● Lists
● Hashtable/ Associative Array/ Dictionary
● Painless Strings
● …
● Basically: Not Re-In...
Abstraction
GLib2
● https://developer.gnome.org/glib/
● Initially developed by GNOME but
separated GTK+ to be used in othe...
Abstraction
GLib2
● „the missing standard library“
● „Boost for C“
● In my opinion the best universal purpose
library for ...
Abstraction
GLib2 List Example
GList *beers = NULL;
beers = g_list_append(beers, g_strdup("Helles"));
beers = g_list_appen...
Error Handling
Error Handling
Back To The Basics
● No fancy stuff like try / catch blocks and
exceptions
● Has to be done manually
● Ther...
Error Handling
Classic Via Return Code
int doCalculations()
{
    int rc = calcSomething();
 
    if (rc != OK)
    {
    ...
Error Handling
A Case For goto
int doCalculations()
{
int rc = calcSomething();
if (rc != OK) goto error_calcSomething;
rc...
Error Handling
A Case For goto
● Only use it for local error handling & clean
up
● The rule: “Jump forward in a function”
...
Error Handling
An empirical study of goto in C code
● University study published in 2015 *
● Analysis of all C code at git...
Error Handling
Conclusion of the Study
We conclude that developers limit
themselves to using goto appropriately in
most ca...
Testing
Testing
Unit Testing Is Universal
● “self testing code” is of course possible in
C as well
● Requires good understanding o...
Testing
A Futter Machine
Testing
The Big Picture
Testing
Test First
Testing
No Such Function
machine_test.c:9:5: warning: implicit declaration of function
‘Machine_create’ [-Wimplicit-functi...
Testing
Provide The Interface
Testing
Implementation Still Missing
/tmp/ccOl0iLr.o: In function
`test_create_machine_with_no_error':
machine_test.c:(.te...
Testing
Provide A Simple Implementation
Testing
The Test Passes
● Now everything required is present:
– Test (our mini application)
– Interface (the header file)
...
Testing
The Big Picture Revisted
Old Friends
Old Friends
Function Pointer
● Define the code to be executed at runtime
● “Typed functional programming”
● “registering a...
Old Friends
Function Pointer Example
// calc functions
int addInt(int a, int b) {return a + b;}
int multiplyInt(int a, int...
Old Friends
Language Bridges
● Integrate C code in other programming
language
● Develop “high level” and fall back when
– ...
Old Friends
Bridging from Python To C (ctypes)
int add(int a, int b) {
return a + b;
}
C function in libmaikmath.so:
impor...
How To Code
How To Code
My Conventions
● Code for the programmer after me - not the
machine
● Rarely use Macros - adds one more
indire...
How To Code
I Like IDEs
● My setup:
– Eclipse CDT with
– VIM plugin and
– Running on Linux in a Vagrant provided Virtualbo...
How To Code
Eclipse CDT Example
Further Reading
Further Reading
Getting Started
[9]
Further Reading
Structure
[10]
Further Reading
Syntax
[11]
Further Reading
Online
● Nice Primer:
http://developer.getpebble.com/tutorials/be
ginner/primer
● How To C in 2016 – good ...
Thank You For Your Attention
[12]
Image References
● [1] - http://www.bilbaoisrock.com/wp-content/uploads/2013/04/the-ramones.jpg
● [2] - https://pragprog.c...
Backup
Abstraction
String Copy Tour
● Scenario
– Copy a string to a new string
– The memory for the new string is smaller than
th...
Abstraction
Strings In C
● NUL (‘0’) terminated array of single bytes
● Example:
char source[] = "abcde";
a b c d e ?? 0
Abstraction
String Copy with strcpy
● First appeared 1975
● Bells/ AT&T: Programmer's Workbench
(PWB/UNIX)
● Renowned for ...
Abstraction
strcpy Example
char source[] = "abcde";
char destination[4] = {0};
0 0 0 0 ?? ????
Content of “destination”:
s...
Abstraction
String Copy with strncpy
● First appeared 1979
● AT&T Unix Version 7
● Found wider usage in the 1990ies to
ove...
Abstraction
strncpy Example
char source[] = "abcde";
char destination[4] = {0};
0 0 0 0 ?? ????
Content of “destination”:
...
Abstraction
String Copy with strlcpy
● First appeared 1998 (OpenBSD)
● Aim:
– No buffer overflows
– Produce always valid C...
Abstraction
strlcpy Example
char source[] = "abcde";
char destination[4] = {0};
0 0 0 0 ?? ????
Content of “destination”:
...
Abstraction
String Copy with strcpy_s
● First appeared 2003 (Microsoft)
● Solves the previous problems
● Is part of C11 st...
Abstraction
strcpy_s Example
char source[] = "abcde";
char destination[4] = {0};
0 0 0 0 ?? ????
Content of “destination”:...
Abstraction
Alternative String Copy Approaches
● Heap based
● Memory allocation automatically
● Must be freed manually
● M...
Abstraction
Alternative String Copy Approaches
● asprintf
– GNU extension of C standard
– Part of glibc
● GLib Strings
– P...
Not Your Fathers C - C Application Development In 2016
Nächste SlideShare
Wird geladen in …5
×

Not Your Fathers C - C Application Development In 2016

611 Aufrufe

Veröffentlicht am

My definition of modern C programming in 2016.

Veröffentlicht in: Software
  • Als Erste(r) kommentieren

  • Gehören Sie zu den Ersten, denen das gefällt!

Not Your Fathers C - C Application Development In 2016

  1. 1. Not Your Fathers C C Application Development In 2016
  2. 2. Introduction About Me ● Living in Leipzig ● five years of exploring ways to write high level C ● C and me is a „convenience marriage“ (Zweck Ehe) ● Other tech stuff: Python, Java ● http://blog.toepfer.nu
  3. 3. Introduction Leipzig Softwerkskammer ● Software Craftsmanship Community in Leipzig ● Once a month ● Mix of coding and beer ● https://www.softwerkskammer.org/groups/ sachsen
  4. 4. Introduction My C Scope ● Application development in a legacy system ● No embedded software ● I am not a kernel hacker
  5. 5. Introduction Why Still C ● Legacy Code ● Embedded systems ● Speed ● Direct Memory Control (Garbage Collection can be slow!)
  6. 6. A Punk Rock Language [1]
  7. 7. A Punk Rock Language Essay in PragProg Magazine March 2011 [2]
  8. 8. A Punk Rock Language 1978 ● Book release and first peak of Punk Rock [4][3]
  9. 9. A Punk Rock Language Three Chords Is Enough To Form A Band [5]
  10. 10. A Punk Rock Language Three Basic Data Types In C [6]
  11. 11. A Punk Rock Language The Craftsman's Question C is quirky, flawed, and an enormous success.. (Dennis Ritchie On C) [7] How To Deal With A Punk Rock Language?
  12. 12. Structure
  13. 13. Structure “On Information Hiding” ● „On the criteria to be used in decomposing systems into modules”, CACM, Dec., 1972 by David L. Parnas. ● Bottom line: Modularization is a very old concept
  14. 14. Structure A C Module ● A *.c file is called a “module” ● Should contain related functions and data ● How to design related functions and data – can't we have classes?
  15. 15. Structure What Is A Class ● A bunch of functions working on (mainly) the same variables. (Uncle Bob) ● That's exactly what we have – how to implement this in C?
  16. 16. Structure Main OO Structure Elements ● Classes – defines an object ● Methods – actions on the object's data ● Packages – organizing classes
  17. 17. Structure A Python Example from long.package.path.my_class import MyClass ... my_instance = MyClass() print(my_instance.say_hello())
  18. 18. Structure Objects in C ● Only function names in global name space ● We need to use a naming convention for structuring: – Class name – Underscore – Method name
  19. 19. Structure Naming Example ● The Module name: MyClass.c ● Functions inside: – The constructor: MyClass_create() – A method: MyClass_sayHello() – The destructor: MyClass_destroy()
  20. 20. Structure Example Ported To C #include "MyClass.h" ... MyClass *my_instance = MyClass_create(); printf("%sn", MyClass_sayHello(my_instance)); MyClass_destroy(my_instance);
  21. 21. Structure Objects in C ● C can give you Object Orientation – Without Inheritance ● It's no real OO – I just call it „Objects in C“ ● Not to be mistaken with *.o files which are compiler result files
  22. 22. Structure Objects In C - My Rules ● treat a C module as a class ● all public functions of that file are the methods of the class ● the first part of the function name is the name of the class ● the second part of the function name is the name of the method ● The first argument of the function is the instance of the object
  23. 23. Structure No Hard Rules ● A module can be designed as an object – but it doesn't have to – simply related functions are still ok. ● I prefer camel case for class and method names but there are other ways as well (see next example). ● As with every convention: – define your rules and stick to it – it's not a religion
  24. 24. Structure Pebble Smart Watch ● Smart watch which started as crowd funding campaign [8]
  25. 25. Structure „Hello Pebble“ Window *window; TextLayer *text_layer; void init() { window = window_create(); text_layer = text_layer_create(GRect(0, 0, 144, 40)); text_layer_set_text(text_layer, "Hello, Pebble!"); layer_add_child(window_get_root_layer(window), text_layer_get_layer(text_layer)); window_stack_push(window, true); } void deinit() { text_layer_destroy(text_layer); window_destroy(window); } int main() { init(); app_event_loop(); deinit(); return 0; }
  26. 26. Abstraction
  27. 27. Abstraction An Old Idea Taken from „The Structure And Interpretation Of Computer Programs“, 2nd Edition, MIT Press, 1996
  28. 28. Abstraction The Standards ● ANSI standard (Strings, Math, Memory) ● Is enhanced by the Posix Standard (Sockets, File descriptors...) ● Covers the bare minimum ● “1000” string functions and non is the right one
  29. 29. Abstraction What I Expect ● Lists ● Hashtable/ Associative Array/ Dictionary ● Painless Strings ● … ● Basically: Not Re-Inventing The Wheel Every Time
  30. 30. Abstraction GLib2 ● https://developer.gnome.org/glib/ ● Initially developed by GNOME but separated GTK+ to be used in other software ● Not to be mistaken with glibc (GNU Implementation of the ANSI and Posix Standards)
  31. 31. Abstraction GLib2 ● „the missing standard library“ ● „Boost for C“ ● In my opinion the best universal purpose library for C – but there are others as well (Apache)
  32. 32. Abstraction GLib2 List Example GList *beers = NULL; beers = g_list_append(beers, g_strdup("Helles")); beers = g_list_append(beers, g_strdup("Pils")); beers = g_list_append(beers, g_strdup("Weizen")); printf("I know %i beers.n", g_list_length(beers)); printf("The third beer is a %s.n", (char*)g_list_nth_data(beers, 2)); GList *iterator = beers; puts("All beers:"); while (iterator != NULL) { printf("%sn", (char*)iterator->data); iterator = g_list_next(iterator); } g_list_free_full(beers, free);
  33. 33. Error Handling
  34. 34. Error Handling Back To The Basics ● No fancy stuff like try / catch blocks and exceptions ● Has to be done manually ● There is a third state: undefined
  35. 35. Error Handling Classic Via Return Code int doCalculations() {     int rc = calcSomething();       if (rc != OK)     {         printf("function calcSomething had an error.n");         return NOT_OK;     }       rc = calcSomethingElse();       if (rc != OK)     {         printf("function calcSomethingElse had an error.n");         return NOT_OK;     }       return OK; }
  36. 36. Error Handling A Case For goto int doCalculations() { int rc = calcSomething(); if (rc != OK) goto error_calcSomething; rc = calcSomethingElse(); if (rc != OK) goto error_calcSomethingElse; return OK; // error handling error_calcSomething: printf("function calcSomething had an error.n"); return NOT_OK; error_calcSomethingElse: printf("function calcSomethingElse had an error.n"); return NOT_OK; }
  37. 37. Error Handling A Case For goto ● Only use it for local error handling & clean up ● The rule: “Jump forward in a function” ● No replacement for „continue“ and „break“ in loops
  38. 38. Error Handling An empirical study of goto in C code ● University study published in 2015 * ● Analysis of all C code at github.com – 2 million lines of Code – 11 000 repositories ● Result – 80 % use goto for error handling – 40% use it for resource clean up * https://peerj.com/preprints/826v1/
  39. 39. Error Handling Conclusion of the Study We conclude that developers limit themselves to using goto appropriately in most cases, and not in an unrestricted manner like Dijkstra feared, thus suggesting that goto does not appear to be harmful in practice.
  40. 40. Testing
  41. 41. Testing Unit Testing Is Universal ● “self testing code” is of course possible in C as well ● Requires good understanding of the code > compile > link > execute cycle ● many unit testing frameworks are available, popular are: – CppuTest – googletest
  42. 42. Testing A Futter Machine
  43. 43. Testing The Big Picture
  44. 44. Testing Test First
  45. 45. Testing No Such Function machine_test.c:9:5: warning: implicit declaration of function ‘Machine_create’ [-Wimplicit-function-declaration] rc = Machine_create(); ^ /tmp/ccThL6ze.o: In function `create_ok': machine_test.c:(.text+0x15): undefined reference to `Machine_create' collect2: error: ld returned 1 exit status ● one warning and one error: – Compiler: Unknown function, auto-detecting prototype missing – Linker: Implementation missing
  46. 46. Testing Provide The Interface
  47. 47. Testing Implementation Still Missing /tmp/ccOl0iLr.o: In function `test_create_machine_with_no_error': machine_test.c:(.text+0x15): undefined reference to `Machine_create' collect2: error: ld returned 1 exit status ● linker still complaining about missing implementation
  48. 48. Testing Provide A Simple Implementation
  49. 49. Testing The Test Passes ● Now everything required is present: – Test (our mini application) – Interface (the header file) – Implementation (the machine.c file)
  50. 50. Testing The Big Picture Revisted
  51. 51. Old Friends
  52. 52. Old Friends Function Pointer ● Define the code to be executed at runtime ● “Typed functional programming” ● “registering a callback” – that’s a function pointer ● Awkward syntax but very useful
  53. 53. Old Friends Function Pointer Example // calc functions int addInt(int a, int b) {return a + b;} int multiplyInt(int a, int b) {return a * b;} int calcInt(int a, int b, int (*calcFunction)(int,int)) { return calcFunction(a, b); } int main(void) { int sum = calcInt(2, 3, addInt); int product = calcInt(2, 3, multiplyInt); printf("Sum is %i, product is %in", sum, product); }
  54. 54. Old Friends Language Bridges ● Integrate C code in other programming language ● Develop “high level” and fall back when – Using existing C library – CPU cycles matter – … ● More likely at application edges than core
  55. 55. Old Friends Bridging from Python To C (ctypes) int add(int a, int b) { return a + b; } C function in libmaikmath.so: import ctypes mylib = ctypes.cdll.LoadLibrary('libmaikmath.so') print('1 + 2 =', mylib.add(1, 2)) Using “add” in a Python program: Warning: Oversimplified
  56. 56. How To Code
  57. 57. How To Code My Conventions ● Code for the programmer after me - not the machine ● Rarely use Macros - adds one more indirection in my head ● Try to keep it plain C pimped with modern libraries - but not a new language (GObject/ GTK, libcello)
  58. 58. How To Code I Like IDEs ● My setup: – Eclipse CDT with – VIM plugin and – Running on Linux in a Vagrant provided Virtualbox – Windows 7 Host ● JetBrains CLion looks promising ● My next try: Visual Studio Code with C/ C++ plugin
  59. 59. How To Code Eclipse CDT Example
  60. 60. Further Reading
  61. 61. Further Reading Getting Started [9]
  62. 62. Further Reading Structure [10]
  63. 63. Further Reading Syntax [11]
  64. 64. Further Reading Online ● Nice Primer: http://developer.getpebble.com/tutorials/be ginner/primer ● How To C in 2016 – good discussion: https://matt.sh/howto-c ● My collection of C tips: http://we-press-buttons.blogspot.de/search/ label/C
  65. 65. Thank You For Your Attention [12]
  66. 66. Image References ● [1] - http://www.bilbaoisrock.com/wp-content/uploads/2013/04/the-ramones.jpg ● [2] - https://pragprog.com/magazines/2011-03/punk-rock-languages ● [3] - https://upload.wikimedia.org/wikipedia/commons/thumb/9/95/The_C_Programming_Language,_First_Edition_Cover_ (2).svg/2000px- The_C_Programming_Language,_First_Edition_Cover_(2).svg.png ● [4] - https://ryebreadrodeo.com/prodimages/cz117.jpg ● [5] - http://blog.sharemyguitar.com/wp-content/uploads/2012/03/SMG-Power-Chord.jpg ● [6] - http://codingfox.com/wp-content/uploads/2013/08/data-types.gif ● [7] - https://upload.wikimedia.org/wikipedia/commons/2/26/Card_reader_segfault.jpg ● [8] - http://cdn.mos.techradar.com/art/Watches/Pebble/Pebble%202/Time_2_Collection-970-80.jpg ● [9] - http://ecx.images-amazon.com/images/I/41%2BbFKtFHjL._SX405_BO1,204,203,200_.jpg ● [10] - https://imagery.pragprog.com/products/173/jgade.jpg?1298589886 ● [11] - http://ecx.images-amazon.com/images/I/51Rs4gK05iL._SX379_BO1,204,203,200_.jpg ● [12] - http://agilebacon.com/wp-content/uploads/2014/07/exhausted-student-with-laptop.jpg
  67. 67. Backup
  68. 68. Abstraction String Copy Tour ● Scenario – Copy a string to a new string – The memory for the new string is smaller than the original one
  69. 69. Abstraction Strings In C ● NUL (‘0’) terminated array of single bytes ● Example: char source[] = "abcde"; a b c d e ?? 0
  70. 70. Abstraction String Copy with strcpy ● First appeared 1975 ● Bells/ AT&T: Programmer's Workbench (PWB/UNIX) ● Renowned for Buffer Overflows
  71. 71. Abstraction strcpy Example char source[] = "abcde"; char destination[4] = {0}; 0 0 0 0 ?? ???? Content of “destination”: strcpy(destination, source); Buffer Overflow a b c d ?? ??0e Content of “destination”:
  72. 72. Abstraction String Copy with strncpy ● First appeared 1979 ● AT&T Unix Version 7 ● Found wider usage in the 1990ies to overcome strcpy problems ● Problem: Does not guarantee a proper C string as result.
  73. 73. Abstraction strncpy Example char source[] = "abcde"; char destination[4] = {0}; 0 0 0 0 ?? ???? Content of “destination”: strncpy(destination, source, sizeof(destination)); No NUL byte ??a b c d? ??? Content of “destination”: Next usage of “destination” will read these bytes until NUL is found.
  74. 74. Abstraction String Copy with strlcpy ● First appeared 1998 (OpenBSD) ● Aim: – No buffer overflows – Produce always valid C Strings (NUL terminated) ● Problems: – Truncates strings (controversial) – No adoption into standards – Third party libs required
  75. 75. Abstraction strlcpy Example char source[] = "abcde"; char destination[4] = {0}; 0 0 0 0 ?? ???? Content of “destination”: strlcpy(destination, source, sizeof(destination)); String content is incomplete ??a b c 0? ??? Content of “destination”:
  76. 76. Abstraction String Copy with strcpy_s ● First appeared 2003 (Microsoft) ● Solves the previous problems ● Is part of C11 standard (optional appendix) ● Currently only available as third party library – “Safe C” by Cisco – https://sourceforge.net/projects/safeclib/
  77. 77. Abstraction strcpy_s Example char source[] = "abcde"; char destination[4] = {0}; 0 0 0 0 ?? ???? Content of “destination”: ??0 0 0 0? ??? Content of “destination”: errno_t result = strcpy_s(destination, sizeof(destination), source);ESLEMAX (length exceeds max)
  78. 78. Abstraction Alternative String Copy Approaches ● Heap based ● Memory allocation automatically ● Must be freed manually ● Must be checked if successful
  79. 79. Abstraction Alternative String Copy Approaches ● asprintf – GNU extension of C standard – Part of glibc ● GLib Strings – Part of Glib – Object like behaviour – Offers functions like “append”, “up”, “down”… ● ...

×