21st Century C, 2nd Edition.pdf - 2n d Ed \u25a0\u25a0 Set up a C programming environment with shell facilities makefiles text editors debuggers and memory

21st Century C, 2nd Edition.pdf - 2n d Ed u25a0u25a0 Set...

This preview shows page 1 out of 408 pages.

You've reached the end of your free preview.

Want to read all 408 pages?

Unformatted text preview: 2n d Ed ■■ Set up a C programming environment with shell facilities, makefiles, text editors, debuggers, and memory checkers ■■ Use Autotools, C’s de facto cross-platform package manager ■■ Learn about the problematic C concepts too useful to discard ■■ Solve C’s string-building problems with C-standard functions ■■ Use modern syntactic features for functions that take structured inputs ■■ Build high-level, object-based libraries and programs ■■ Perform advanced math, talk to internet servers, and run databases with existing C libraries and cc? Does C memory management still plague you as it did in the '90s? Ben Klemens capably addresses these and other common problems, demonstrating how tools have emerged to make C programming easier— helping you debug, track down memory leaks, organize the compilation process, and manage source code versions. ” —Dave Kitabjian Director of Software Development, NetCarrier Telecom This edition also includes new material on concurrent threads, virtual tables, C99 numeric types, and other features. C Twitter: @oreillymedia facebook.com/oreilly Klemens US $49.99 21st Century C TIPS FROM THE NEW SCHOOL Ben Klemens has written statistical analyses and computationally intensive models for the Brookings Institution, World Bank, National Institute of Mental Health, and the US government. He has also worked with Brookings and the Free Software Foundation to ensure that authors retain the right to use the software they write. He currently leads a statistical computing group in the research division of the United States Census Bureau. PROGR AMMING/C on C isn’t just the foundation of modern programming languages; it is a modern language, ideal for writing efficient, state-of-the-art applications. Get past idioms that made sense on mainframes and learn the tools you need to work with this evolved and aggressively simple language. No matter what programming language you currently favor, you’ll quickly see that 21st century C rocks. your C development “Isenvironment limited to vi SECOND EDITION 21st Century C Throw out your old ideas about C and get to know a programming language that has substantially outgrown its origins. With this revised edition of 21st Century C, you’ll discover up-to-date techniques missing from other C tutorials, whether you’re new to the language or just getting reacquainted. iti 21st Century C CAN $52.99 ISBN: 978-1-491-90389-6 Ben Klemens 2n d Ed ■■ Set up a C programming environment with shell facilities, makefiles, text editors, debuggers, and memory checkers ■■ Use Autotools, C’s de facto cross-platform package manager ■■ Learn about the problematic C concepts too useful to discard ■■ Solve C’s string-building problems with C-standard functions ■■ Use modern syntactic features for functions that take structured inputs ■■ Build high-level, object-based libraries and programs ■■ Perform advanced math, talk to internet servers, and run databases with existing C libraries and cc? Does C memory management still plague you as it did in the '90s? Ben Klemens capably addresses these and other common problems, demonstrating how tools have emerged to make C programming easier— helping you debug, track down memory leaks, organize the compilation process, and manage source code versions. ” —Dave Kitabjian Director of Software Development, NetCarrier Telecom This edition also includes new material on concurrent threads, virtual tables, C99 numeric types, and other features. C Twitter: @oreillymedia facebook.com/oreilly Klemens US $49.99 21st Century C TIPS FROM THE NEW SCHOOL Ben Klemens has written statistical analyses and computationally intensive models for the Brookings Institution, World Bank, National Institute of Mental Health, and the US government. He has also worked with Brookings and the Free Software Foundation to ensure that authors retain the right to use the software they write. He currently leads a statistical computing group in the research division of the United States Census Bureau. PROGR AMMING/C on C isn’t just the foundation of modern programming languages; it is a modern language, ideal for writing efficient, state-of-the-art applications. Get past idioms that made sense on mainframes and learn the tools you need to work with this evolved and aggressively simple language. No matter what programming language you currently favor, you’ll quickly see that 21st century C rocks. your C development “Isenvironment limited to vi SECOND EDITION 21st Century C Throw out your old ideas about C and get to know a programming language that has substantially outgrown its origins. With this revised edition of 21st Century C, you’ll discover up-to-date techniques missing from other C tutorials, whether you’re new to the language or just getting reacquainted. iti 21st Century C CAN $52.99 ISBN: 978-1-491-90389-6 Ben Klemens SECOND EDITION 21st Century C Ben Klemens 21st Century C, Second Edition by Ben Klemens Copyright © 2015 Ben Klemens. All rights reserved. Printed in the United States of America. Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472. O’Reilly books may be purchased for educational, business, or sales promotional use. Online editions are also available for most titles ( ). For more information, contact our cor‐ porate/institutional sales department: 800-998-9938 or [email protected] Editors: Rachel Roumeliotis and Allyson MacDonald Production Editor: Nicole Shelby Copyeditor: Becca Freed Proofreader: Amanda Kersey September 2014: Indexer: Judy McConville Interior Designer: David Futato Cover Designer: Karen Montgomery Illustrator: Rebecca Demarest Second Edition Revision History for the Second Edition 2014-09-24: First Release See for release details. The O’Reilly logo is a registered trademark of O’Reilly Media, Inc. 21st Century C, the cover image, and related trade dress are trademarks of O’Reilly Media, Inc. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and O’Reilly Media, Inc., was aware of a trade‐ mark claim, the designations have been printed in caps or initial caps. While the publisher and the author have used good faith efforts to ensure that the information and instructions contained in this work are accurate, the publisher and the author disclaim all responsibility for errors or omissions, including without limitation responsibility for damages resulting from the use of or reliance on this work. Use of the information and instructions contained in this work is at your own risk. If any code samples or other technology this work contains or describes is subject to open source licenses or the intellectual property rights of others, it is your responsibility to ensure that your use thereof complies with such licenses and/or rights. 978-1-491-90389-6 [LSI] Table of Contents Preface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ix Part I. The Environment 1. Set Yourself Up for Easy Compilation. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 Use a Package Manager Compiling C with Windows POSIX for Windows Compiling C with POSIX Compiling C Without POSIX Which Way to the Library? A Few of My Favorite Flags Paths Runtime Linking Using Makefiles Setting Variables The Rules Using Libraries from Source Using Libraries from Source (Even if Your Sysadmin Doesn’t Want You To) Compiling C Programs via Here Document Include Header Files from the Command Line The Unified Header Here Documents Compiling from stdin 2 4 4 6 7 8 10 11 14 15 15 18 22 23 25 25 26 27 28 2. Debug, Test, Document. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31 Using a Debugger 31 iii A Debugging Detective Story GDB Variables Print Your Structures Using Valgrind to Check for Errors Unit Testing Using a Program as a Library Coverage Error Checking What is the User’s Involvement in the Error? The Context in Which the User is Working How Should the Error Indication Be Returned? Interweaving Documentation Doxygen Literate Code with CWEB 34 43 44 48 50 53 54 55 56 57 59 59 60 61 3. Packaging Your Project. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65 The Shell Replacing Shell Commands with Their Outputs Use the Shell’s for Loops to Operate on a Set of Files Test for Files fc Makefiles vs. Shell Scripts Packaging Your Code with Autotools An Autotools Demo Describing the Makefile with Makefile.am The configure Script 66 67 68 70 73 75 77 79 82 87 4. Version Control. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93 Changes via diff Git’s Objects The Stash Trees and Their Branches Merging The Rebase Remote Repositories 94 95 99 100 101 103 104 5. Playing Nice with Others. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107 Dynamic Loading The Limits of Dynamic Loading The Process Writing to Be Read by Nonnatives The Wrapper Function iv | 107 110 110 111 111 Table of Contents Smuggling Data Structures Across the Border Linking Python Host Compiling and Linking The Conditional Subdirectory for Automake Distutils Backed with Autotools Part II. 112 114 114 116 116 118 The Language 6. Your Pal the Pointer. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123 Automatic, Static, and Manual Memory Persistent State Variables Pointers Without malloc Structures Get Copied, Arrays Get Aliased malloc and Memory-Twiddling The Fault Is in Our Stars All the Pointer Arithmetic You Need to Know Typedef as a teaching tool 123 128 129 131 134 135 136 139 7. Inessential C Syntax that Textbooks Spend a Lot of Time Covering. . . . . . . . . . . . . . . . 141 Don’t Bother Explicitly Returning from main Let Declarations Flow Set Array Size at Runtime Cast Less Enums and Strings Labels, gotos, switches, and breaks goto Considered switch Deprecate Float Comparing Unsigned Integers Safely Parse Strings to Numbers 141 142 144 145 147 148 149 152 153 156 156 8. Important C Syntax that Textbooks Often Do Not Cover. . . . . . . . . . . . . . . . . . . . . . . . . 161 Cultivate Robust and Flourishing Macros The Preprocessor Test Macros Header Guards Linkage with static and extern Externally Linked Variables in Header Files The const Keyword Noun-Adjective Form 161 166 170 172 174 175 177 178 Table of Contents | v Tension Depth The char const ** Issue 179 179 180 9. Easier Text Handling. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185 Making String Handling Less Painful with asprintf Security Constant Strings Extending Strings with asprintf A Pæan to strtok Unicode The Encoding for C Code Unicode Libraries The Sample Code 185 188 189 191 192 197 199 200 201 10. Better Structures. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205 Compound Literals Initialization via Compound Literals Variadic Macros Safely Terminated Lists Multiple Lists Foreach Vectorize a Function Designated Initializers Initialize Arrays and Structs with Zeros Typedefs Save the Day A Style Note Return Multiple Items from a Function Reporting Errors Flexible Function Inputs Declare Your Function as printf-Style Optional and Named Arguments Polishing a Dull Function The Void Pointer and the Structures It Points To Functions with Generic Inputs Generic Structures 206 207 208 209 210 212 212 214 216 217 218 220 221 223 224 226 228 234 234 239 11. Object-Oriented Programming in C. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 245 Extending Structures and Dictionaries Implementing a Dictionary C, with fewer seams Functions in Your Structs vi | 247 249 253 258 Table of Contents Vtables Scope Private Struct Elements Overload _Generic Count References Example: A Substring Object Example: An Agent-Based Model of Group Formation Conclusion 262 267 268 270 271 274 275 279 286 12. Parallel Threads. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 289 The Environment The Ingredients OpenMP Compiling OpenMP, pthreads, and C atoms Interference Map-reduce Multiple Tasks Thread Local Localizing Nonstatic Variables Shared Resources Atoms Pthreads C atoms Atomic structs 290 291 292 294 295 296 297 298 300 300 305 308 312 315 13. Libraries. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 321 GLib POSIX Parsing Regular Expressions Using mmap for Gigantic Data Sets The GNU Scientific Library SQLite The Queries libxml and cURL 321 322 322 327 330 332 334 335 Epilogue. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 341 A. C 101. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 343 Table of Contents | vii Glossary. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 363 References. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 367 Index. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 371 viii | Table of Contents Preface Is it really punk rock Like the party line? —Wilco, “Too Far Apart” C Is Punk Rock C has only a handful of keywords and is a bit rough around the edges, and it rocks. You can do anything with it. Like the C, G, and D chords on a guitar, you can learn the basic mechanics quickly, and then spend the rest of your life getting better. The people who don’t get it fear its power and think it too edgy to be safe. By all rankings, it is consistently the most popular language that doesn’t have a corporation or foun‐ dation spending money to promote it.1 Also, the language is about 40 years old, which makes it middle-aged. It was written by a few guys basically working against management—the perfect punk rock ori‐ gins—but that was in the 1970s, and there’s been a lot of time for the language to go mainstream. What did people do when punk rock went mainstream? In the decades since its advent in the 1970s, punk certainly has come in from the fringes: The Clash, The Off‐ spring, Green Day, and The Strokes sold millions of albums worldwide (to name just a few), and I have heard lite instrumental versions of songs from the punk spinoff known as grunge at my local supermarket. The former lead singer of Sleater-Kinney now has a popular sketch comedy show that frequently lampoons punk rockers.2 One reaction to the continuing evolution would be to take the hard line and say that the 1 This preface owes an obvious and huge debt to Punk Rock Languages: A Polemic by Chris Adamson. 2 With lyrics like “Can’t get to heaven with a three-chord song,” maybe Sleater-Kinney was post-punk? Unfortu‐ nately, there is no ISO punk standard we can look to for precise in-or-out definitions. ix original stuff was punk and everything else is just easy punk pop for the masses. The traditionalists can still play their albums from the ’70s, and if the grooves are worn out, they can download a digitally mastered edition. They can buy Ramones hoodies for their toddlers. Outsiders don’t get it. Some of them hear the word punk and picture something out of the 1970s—a historic artifact about some kids that were, at the time, really doing something different. The traditionalist punks who still love and play their 1973 Iggy Pop LPs are having their fun, but they bolster the impression that punk is ossified and no longer relevant. Getting back to the world of C, we have both the traditionalists, waving the banner of ANSI ’89, and those who will rock out to whatever works and may not even realize that the code they are writing would not have compiled or run in the 1990s. Outsiders don’t get the difference. They see still-in-print books from the 1980s and still-online tutorials from the 1990s, they hear from the hardcore traditionalists who insist on still writing like that today, and they don’t even know that the language and the rest of its users continue to evolve. That’s a shame, because they’re missing out on some great stuff. This is a book about breaking tradition and keeping C punk rock. I don’t care to com‐ pare the code in this book to the original C specification in Kernighan & Ritchie’s 1978 book. My telephone has 512 MB of memory, so why are our C textbooks still spending pages upon pages covering techniques to shave kilobytes off of our executa‐ bles? I am writing this on a bottom-of-the-line red netbook that can accommodate 3,200,000,000 instructions per second; what do I care about whether an operation requires comparing 8 bits or 16? We should be writing code that we can write quickly and that is readable by our fellow humans. We’re still writing in C, so our readable but imperfectly optimized code will still run an order of magnitude faster than if we’d written comparable code in any number of alternative, bloated languages. Q & A (Or, the Parameters of the Book) Q: How is this C book different from all others? A: Some are better written, some are even entertaining, but C textbooks are a some‐ what uniform bunch (I’ve read a lot of them, including C for Programmers with an Introduction to C11; Head First C; The C Programming Language, 1st Edition; The C Programming Language 2nd Edition; Programming in C; Practical C Programming; Absolute Beginner’s Guide to C; The Waite Group’s C Primer Plus; and C Programming). Most were written before the C99 standard simplified many aspects of usage, and you can tell that some of those now in their nth edition just pasted in a few notes about updates rather than seriously rethinking how to use the language. They all mention that there might be libraries that you could maybe use in writing your own code, but x | Preface most predate the installation tools and ecosystem we have now, which make using those libraries reliable and reasonably portable. Those textbooks are still valid and still have value, but modern C code just doesn’t look like much of the code in many of those textbooks. This book picks up where they left off, reconsidering the language and the ecosystem in which it lives. The storyline here is about using libraries that provide linked lists and XML parsers, not writing new ones from scratch. It is about writing code that is readable and has a friendly user interface. Q: Who is this book for? Do I need to be a coding guru? A: You have experience coding in any language, maybe Java or a scripting language such as Perl. I don’t have to sell you on why your code shouldn’t be one long routine with no subfunctions. The body of the book assumes basic knowledge of C gained from time spent writing C code. If you are rusty on the details or are starting from zero, Appendix A offers a short tutorial on basic C for readers who are coming from a scripting language like Python or Ruby. I might as well point out to you that I have also written a textbook on statistical and scientific computing, Modeling with Data (Klemens, 2008). Along with lots of details of dealing with numeric data and using statistical models for describing data, it has a longer, more standalone tutorial on C, which I naturally think overcomes many of the failings of older C tutorials. Q: I’m an application programmer, not a kernel hacker. Why s...
View Full Document

  • Winter '15
  • JANE SMITH

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture

Stuck? We have tutors online 24/7 who can help you get unstuck.
A+ icon
Ask Expert Tutors You can ask You can ask You can ask (will expire )
Answers in as fast as 15 minutes