Statistics
16
Views
0
Downloads
0
Donations
Uploader

高宏飞

Shared on 2025-12-21
Support
Share

AuthorPeter Prinz, Tony Crawford

The new edition of this classic O’Reilly reference provides clear, detailed explanations of every feature in the C language and runtime library, including multithreading, type-generic macros, and library functions that are new in the 2011 C standard (C11). If you want to understand the effects of an unfamiliar function, and how the standard library requires it to behave, you’ll find it here, along with a typical example. Ideal for experienced C and C++ programmers, this book also includes popular tools in the GNU software collection. You’ll learn how to build C programs with GNU Make, compile executable programs from C source code, and test and debug your programs with the GNU debugger. In three sections, this authoritative book covers: C language concepts and language elements, with separate chapters on types, statements, pointers, memory management, I/O, and more The C standard library, including an overview of standard headers and a detailed function reference Basic C programming tools in the GNU software collection, with instructions on how use them with the Eclipse IDE

Tags
No tags
ISBN: 1491904755
Publisher: O’Reilly Media
Publish Year: 2015
Language: 英文
Pages: 824
File Format: PDF
File Size: 9.0 MB
Support Statistics
¥.00 · 0times
Text Preview (First 20 pages)
Registered users can read the full content for free

Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.

Peter Prinz & Tony Crawford C in a Nutshell THE DEFINITIVE REFERENCE 2nd Edition Covers C11 standard
(This page has no text content)
C IN A NUTSHELL Second Edition Peter Prinz and Tony Crawford
978-1-491-90475-6 [M] C in a Nutshell, Second Edition by Peter Prinz and Tony Crawford Copyright © 2016 Peter Prinz and Tony Crawford. 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 (http://safaribooksonline.com). For more information, contact our corporate/institutional sales department: 800-998-9938 or corporate@oreilly.com. Editors: Rachel Roumeliotis and Katie Schooling Production Editor: Kristen Brown Copyeditor: Gillian McGarvey Proofreader: Jasmine Kwityn Indexer: Angela Howard Interior Designer: David Futato Cover Designer: Karen Montgomery Illustrator: Rebecca Demarest December 2005: First Edition December 2015: Second Edition Revision History for the Second Edition 2015-12-07: First Release See http://oreilly.com/catalog/errata.csp?isbn=9781491904756 for release details. The O’Reilly logo is a registered trademark of O’Reilly Media, Inc. C in a Nutshell, Second Edition, the cover image of a cow, and related trade dress are trademarks of O’Reilly Media, Inc. While the publisher and the authors have used good faith efforts to ensure that the informa‐ tion and instructions contained in this work are accurate, the publisher and the authors dis‐ claim 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 technol‐ ogy this work contains or describes is subject to open source licenses or the intellectual prop‐ erty rights of others, it is your responsibility to ensure that your use thereof complies with such licenses and/or rights.
Table of Contents Preface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ix Part I. Language 1. Language Basics. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 Characteristics of C 3 The Structure of C Programs 4 Source Files 6 Comments 7 Character Sets 8 Identifiers 14 How the C Compiler Works 19 2. Types. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23 Typology 23 Integer Types 24 Floating-Point Types 30 Complex Floating-Point Types 32 Enumerated Types 33 The Type void 34 The Alignment of Objects in Memory 36 3. Literals. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39 Integer Constants 39 Floating-Point Constants 40 Character Constants 42 String Literals 45 4. Type Conversions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49 Conversion of Arithmetic Types 50 Conversion of Nonarithmetic Types 58 iii
5. Expressions and Operators. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67 How Expressions Are Evaluated 68 Operators in Detail 73 Constant Expressions 97 6. Statements. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99 Expression Statements 99 Block Statements 100 Loops 101 Selection Statements 105 Unconditional Jumps 108 7. Functions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113 Function Definitions 113 Function Declarations 120 How Functions Are Executed 122 Pointers as Arguments and Return Values 122 Inline Functions 123 Non-Returning Functions 125 Recursive Functions 126 Variable Numbers of Arguments 127 8. Arrays. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129 Defining Arrays 129 Accessing Array Elements 131 Initializing Arrays 132 Strings 134 Multidimensional Arrays 136 Arrays as Arguments of Functions 138 9. Pointers. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141 Declaring Pointers 141 Operations with Pointers 144 Pointers and Type Qualifiers 148 Pointers to Arrays and Arrays of Pointers 152 Pointers to Functions 156 10. Structures, Unions, and Bit-Fields. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159 Structures 159 Unions 169 Anonymous Structures and Unions 171 Bit-Fields 172 iv | Table of Contents
11. Declarations. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 175 Object and Function Declarations 176 Type Names 184 typedef Declarations 185 _Static_assert Declarations 186 Linkage of Identifiers 187 Storage Duration of Objects 189 Initialization 190 12. Dynamic Memory Management. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 193 Allocating Memory Dynamically 194 Characteristics of Allocated Memory 195 Resizing and Releasing Memory 196 An All-Purpose Binary Tree 198 Characteristics 198 Implementation 199 13. Input and Output. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209 Streams 209 Files 211 Opening and Closing Files 213 Reading and Writing 216 Random File Access 235 14. Multithreading. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 239 Threads 240 Accessing Shared Data 244 Communication Between Threads: Condition Variables 251 Thread-Local Objects and Thread-Specific Storage 256 15. Preprocessing Directives. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 261 Inserting the Contents of Header Files 262 Defining and Using Macros 264 Type-generic Macros 272 Conditional Compiling 272 Defining Line Numbers 274 Generating Error Messages 275 The #pragma Directive 275 The _Pragma Operator 276 Predefined Macros 277 Table of Contents | v
Part II. Standard Library 16. The Standard Headers. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 283 Using the Standard Headers 284 Functions with Bounds-Checking 287 Contents of the Standard Headers 289 17. Functions at a Glance. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 321 Input and Output 321 Mathematical Functions 323 Character Classification and Conversion 330 String Processing 332 Multibyte Characters 333 Converting Between Numbers and Strings 335 Searching and Sorting 336 Memory Block Handling 336 Dynamic Memory Management 337 Date and Time 337 Process Control 339 Internationalization 340 Nonlocal Jumps 341 Multithreading (C11) 341 Debugging 345 Error Messages 346 18. Standard Library Functions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 349 Part III. Basic Tools 19. Compiling with GCC. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 669 The GNU Compiler Collection 669 Obtaining and Installing GCC 670 Compiling C Programs with GCC 671 C Dialects 681 Compiler Warnings 683 Optimization 684 Debugging 688 Profiling 688 Option and Environment Variable Summary 689 vi | Table of Contents
20. Using make to Build C Programs. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 695 Targets, Prerequisites, and Commands 695 The Makefile 696 Rules 696 Comments 703 Variables 704 Phony Targets 711 Other Target Attributes 712 Macros 714 Functions 715 Directives 719 Running make 722 21. Debugging C Programs with GDB. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 731 Installing GDB 732 A Sample Debugging Session 732 Starting GDB 736 Using GDB Commands 741 Analyzing Core Files in GDB 763 22. Using an IDE with C. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 767 IDEs for C 767 The Eclipse IDE for C/C++ 768 Developing a C Program with Eclipse 770 Debugging a C Program in Eclipse 773 Further Information on Eclipse 776 Index. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 777 Table of Contents | vii
(This page has no text content)
Preface This book is a complete reference to the C programming language and the C run‐ time library. As an “In a Nutshell” book, its purpose is to serve as a convenient, reli‐ able companion for C programmers in their day-to-day work. It describes all the elements of the language and illustrates their use with numerous examples. The present description of the C language is based on the 2011 international C stan‐ dard, ISO/IEC 9899:2011, widely known as C11. This standard supersedes the C99 standard, ISO/IEC 9899:1999, and its Technical Corrigenda, TC1 of 2001, TC2 of 2004, and TC3 of 2007. The first international C standard, ISO/IEC 9899:1990, was published in 1990 and supplemented in 1995 by Normative Addendum 1 (ISO/IEC 9899/AMD1:1995). The 1990 ISO/IEC standard corresponds to the ANSI standard X3.159, which was ratified in late 1989 and is commonly called ANSI C or C89. The new features of the 2011 C standard are not yet fully supported by all compilers and standard library implementations. In this book, we have therefore labeled 2011 features—such as multithreading, type-generic macros, and new standard library functions—with the abbreviation C11. Extensions that were introduced by the C99 standard are labeled with the abbreviation C99. This book is not an introduction to programming in C. Although it covers the fun‐ damentals of the language, it is not organized or written as a tutorial. If you are new to C, we assume that you have read at least one of the many introductory books, or that you are familiar with a related language, such as Java or C++. How This Book Is Organized This book is divided into three parts. The first part describes the C language in the strict sense of the term; the second part describes the standard library; and the third part describes the process of compiling and testing programs with the popular tools in the GNU software collection. ix
Part I Part I, which deals with the C language, includes Chapters 1 through 15. After Chapter 1, which describes the general concepts and elements of the language, each chapter is devoted to a specific topic, such as types, statements, or pointers. Although the topics are ordered so that the fundamental concepts for each new topic have been presented in an earlier chapter—types, for example, are described before expressions and operators, which come before statements, and so on—you may sometimes need to follow references to later chapters to fill in related details. For example, some discussion of pointers and arrays is necessary in Chapter 5 (which covers expressions and operators), even though pointers and arrays are not described in full detail until Chapters 8 and 9. Chapter 1, “Language Basics” Describes the characteristics of the language and how C programs are struc‐ tured and compiled. This chapter introduces basic concepts such as the transla‐ tion unit, character sets, and identifiers. Chapter 2, “Types” Provides an overview of types in C and describes the basic types, the type void, and enumerated types. Chapter 3, “Literals” Describes numeric constants, character constants, and string literals, including escape sequences. Chapter 4, “Type Conversions” Describes implicit and explicit type conversions, including integer promotion and the usual arithmetic conversions. Chapter 5, “Expressions and Operators” Describes the evaluation of expressions, all the operators, and their compatible operands. Chapter 6, “Statements” Describes C statements such as blocks, loops, and jumps. Chapter 7, “Functions” Describes function definitions and function calls, including recursive and inline functions. Chapter 8, “Arrays” Describes fixed-length and variable-length arrays, including strings, array initi‐ alization, and multidimensional arrays. Chapter 9, “Pointers” Describes the definition and use of pointers to objects and functions. Chapter 10, “Structures, Unions, and Bit-Fields” Describes the organization of data in these user-defined derived types. x | Preface
Chapter 11, “Declarations” Describes the general syntax of a declaration, identifier linkage, and the storage duration of objects. Chapter 12, “Dynamic Memory Management” Describes the standard library’s dynamic memory management functions, illustrating their use in a sample implementation of a generalized binary tree. Chapter 13, “Input and Output” Describes the C concept of input and output, with an overview of the use of the standard I/O library. Chapter 14, “Multithreading” Describes the use of the C11 multithreading features, including atomic opera‐ tions, communication between threads, and thread-specific storage. Chapter 15, “Preprocessing Directives” Describes the definition and use of macros, conditional compiling, and all the other preprocessor directives and operators. Part II Part II, consisting of Chapters 16, 17, and 18, is devoted to the C standard library. It provides an overview of standard headers and also contains a detailed function ref‐ erence. Chapter 16, “The Standard Headers” Describes contents of the headers and their use. The headers contain all of the standard library’s macros and type definitions. Chapter 17, “Functions at a Glance” Provides an overview of the standard library functions, organized by areas of application (e.g., mathematical functions, date and time functions, etc.). Chapter 18, “Standard Library Functions” Describes each standard library function in detail, in alphabetical order, and contains examples to illustrate the use of each function. Part III The third part of this book, which includes Chapters 19 through 20, provides the necessary knowledge of the C programmer’s basic tools: the compiler, the make util‐ ity, and the debugger. The tools described here are those in the GNU software col‐ lection. Finally, the use of these tools in an integrated development environment (IDE) for C is described using the Eclipse IDE as an example. Chapter 19, “Compiling with GCC” Describes the principal capabilities that the widely used compiler offers for C programmers. Preface | xi
Chapter 20, “Using make to Build C Programs” Describes how to use the make program to automate the compiling process for large programs. Chapter 21, “Debugging C Programs with GDB” Describes how to run a program under the control of the GNU debugger and how to analyze programs’ runtime behavior to find logical errors. Chapter 22, “Using an IDE with C” Describes the use of an integrated development environment (IDE) for unified, convienient access to all the tools for developing C programs. Further Reading In addition to works mentioned at appropriate points in the text, there are a num‐ ber of resources for readers who want more technical detail than even this book can provide. The international working group on C standardization has an official home page at http://www.open-std.org/jtc1/sc22/wg14, with links to the latest version of the C standard and current projects of the working group. For readers who are interested in not only the what and how of C, but also the why, the WG14 site also offers links to some of its drafts and rationales. These documents describe some of the motivations and constraints involved in the standardization process. Furthermore, for those who may wonder how C “got to be that way” in the first place, the originator of C, the late Dennis Ritchie, wrote an article titled “The Development of the C Language”. This and other historical documents are still available on his Bell Labs website, https://www.bell-labs.com/usr/dmr/www/ index.html. Readers who want details on floating-point math beyond the scope of C may wish to start with David Goldberg’s thorough introduction, “What Every Computer Scien‐ tist Should Know About Floating-Point Arithmetic,” currently available online at http://docs.sun.com/source/806-3568/ncg_goldberg.html. Conventions Used in This Book The following typographical conventions are used in this book: Italic Highlights new terms; indicates filenames, file extensions, URLs, directories, and Unix utilities. Constant width Indicates all elements of C source code: keywords, operators, variables, func‐ tions, macros, types, parameters, and literals. Also used for console commands and options, and the output from such commands. xii | Preface
Constant width bold Highlights the function or statement under discussion in code examples. In compiler, make, and debugger sessions, this font indicates command input to be typed literally by the user. Constant width italic Indicates parameters in function prototypes, or placeholders to be replaced with your own values. Plain text Indicates keys such as Return, Tab, and Ctrl. This element signifies a tip or suggestion. This element signifies a general note. This element indicates a warning or caution. Using Code Examples Supplemental material (code examples, exercises, etc.) is available for download at https://github.com/oreillymedia/c-in-a-nutshell-2E. This book is here to help you get your job done. In general, if example code is offered with this book, you may use it in your programs and documentation. You do not need to contact us for permission unless you’re reproducing a significant por‐ tion of the code. For example, writing a program that uses several chunks of code from this book does not require permission. Selling or distributing a CD-ROM of examples from O’Reilly books does require permission. Answering a question by citing this book and quoting example code does not require permission. Incorporat‐ ing a significant amount of example code from this book into your product’s docu‐ mentation does require permission. We appreciate, but do not require, attribution. An attribution usually includes the title, author, publisher, and ISBN. For example: “C in a Nutshell, 2nd Edition by Preface | xiii
Peter Prinz and Tony Crawford (O’Reilly). Copyright 2016 Peter Prinz, Tony Craw‐ ford, 978-1-491-90475-6.” If you feel your use of code examples falls outside fair use or the permission given above, feel free to contact us at permissions@oreilly.com. Safari® Books Online Safari Books Online is an on-demand digital library that delivers expert content in both book and video form from the world’s leading authors in technology and business. Technology professionals, software developers, web designers, and business and creative professionals use Safari Books Online as their primary resource for research, problem solving, learning, and certification training. Safari Books Online offers a range of plans and pricing for enterprise, government, education, and individuals. Members have access to thousands of books, training videos, and prepublication manuscripts in one fully searchable database from publishers like O’Reilly Media, Prentice Hall Professional, Addison-Wesley Professional, Microsoft Press, Sams, Que, Peachpit Press, Focal Press, Cisco Press, John Wiley & Sons, Syngress, Morgan Kaufmann, IBM Redbooks, Packt, Adobe Press, FT Press, Apress, Manning, New Riders, McGraw-Hill, Jones & Bartlett, Course Technology, and hundreds more. For more information about Safari Books Online, please visit us online. How to Contact Us Please address comments and questions concerning this book to the publisher: O’Reilly Media, Inc. 1005 Gravenstein Highway North Sebastopol, CA 95472 800-998-9938 (in the United States or Canada) 707-829-0515 (international or local) 707-829-0104 (fax) We have a web page for this book, where we list errata, examples, and any additional information. You can access this page at http://bit.ly/C_Nutshell_2e. To comment or ask technical questions about this book, send email to bookques‐ tions@oreilly.com. For more information about our books, courses, conferences, and news, see our website at http://www.oreilly.com. xiv | Preface
Find us on Facebook: http://facebook.com/oreilly Follow us on Twitter: http://twitter.com/oreillymedia Watch us on YouTube: http://www.youtube.com/oreillymedia Acknowledgments Both of us want to thank everyone at O’Reilly for their fantastic work on our book, and especially our editors, Rachel Roumeliotis and Katie Schooling, for all their guidance along the way. We also thank our technical reviewers, Matt Crawford, David Kitabjian, Chris LaPre, John C. Craig, and Loïc Pefferkorn, for their valuable criticism of our manuscript, and we’re grateful to our production editor, Kristen Brown, and our copyeditor, Gillian McGarvey, for all their attention to making our book look good and bringing our style up to date. Finally, thanks to Jonathan Gen‐ nick for setting the whole project in motion all those years ago. Peter I would like to thank Tony, first of all, for the excellent collaboration. My heartfelt thanks also go to all my friends for the understanding they showed again and again when I had so little time for them. Last but not least, I dedicate this book to my daughters, Vivian and Jeanette—both of them now PhDs in computer science—who strengthened my ambition to carry out this book project. Tony I thank Peter for letting me take all the space I could fill in this project. Preface | xv
(This page has no text content)
I Language
(This page has no text content)
The above is a preview of the first 20 pages. Register to read the complete e-book.