You will learn about the following in this chapter:
- C’s history and features
- The steps needed to write programs
- A bit about compilers and linkers
- C standards
Whenence C?
Why C?
在过去四十多年,C 语言一直都是非常流行和发挥重要作用的编程语言。但是在过去十多年,大部分人却从 C 语言转向类似 C++,Objective C 和 Java 语言。(因为面向对象过程的开发效率远远高于面向过程,也就是 C 语言要不停造轮子!)但是学好 C 语言,你可以快速学会其它语言。C 语言有以下四大优点
Design Features | - Powerful control structures - top-down planning, structured programming, and modular design |
---|---|
Efficiency:Fast | In fact, C exhibits some of the fine control usually associated with an assembly language. An assembly language is a mnemonic representation of the set of internal instructions used by a particular central processing unit design; different CPU families have different assembly languages. |
Portability 对于特定硬件可移植性不好 |
- C is a portable language, which means that C programs written on one system can be run on other systems with little or no modification. - C compilers (programs that convert your C code into the instructions a computer uses internally) are available for many computer architectures, running from 8-bit microprocessors to Cray supercomputers. |
Power and Flexibility | - powerful: most of the powerful, flexible Unix operating system was written in C; Many compilers and interpreters for other languages—such as FORTRAN, Perl, Python, Pascal, LISP, Logo, and BASIC—have been written in C. - C programs have been used for solving physics and engineering problems and even for animating special effects for movies. |
Programmer Oriented C gives you more freedom, but it also puts more responsibility on you. |
- It gives you access to hardware, and it enables you to manipulate individual bits in memory. - C is less strict than, say, Pascal or even C++ in limiting what you can do. - The advantage is that many tasks, such as converting forms of data, are much simpler in C. - The danger is that with C, you can make mistakes that are impossible in some languages. - most C implementations have a large library of useful C functions. |
Shortcomings | 1. C’s use of pointers (something you can look forward to learning about in this book), in particular, means that you can make programming errors that are difficult to trace. 1. the price of liberty is eternal vigilance. |
Whither C?
By the early 1980s, C was already a dominant language in the minicomputer world of Unix systems. Since then, it has spread to personal computers (microcomputers) and to mainframes (the big guys).
In the 1990s, many software houses began turning to the C++ language for large program-ming projects. C++ grafts object-oriented programming tools to the C language. ( Object-oriented programming is a philosophy that attempts to mold the language to fit a problem instead of molding the problem to fit the language.)
Despite the popularity of newer languages, such as C++ and Java, C remains a core skill in the software business, typically ranking in the top 10 of desired skills. In particular, C has become popular for programming embedded systems. Also, C has been making inroads in FORTRAN’s long dominance of scientific programming. Finally, as befits a language created to develop an operating system, it plays a strong role in the development of Linux. Thus, the second decade of the twenty-first century finds C still going strong.
截至 2021/4/3 日,C 语言处于流行度第一,图片来自 TIOBE 官网
What Computers Do?
This knowledge will help you understand the connection between writing a program in C and what eventually takes place when you run that program. Modern computers have several components.
The central processing unit, or CPU | Does most of the computing work |
---|---|
The random access memory, or RAM | Serves as a workspace to hold programs and files |
The permanent memory storage device ( |
Remembers those programs and files, even while the computer is turned off |
various peripherals | such as the keyboard, mouse, touchscreen, and monitor—provide for communication between the computer and you |
:::tips peripheral
- US: [pə’rɪf(ə)rəl] UK: [pə’rɪf(ə)rəl]
- adj.周围的;外面的;边缘的;【解】(神经)末梢区域的
- Web 外设;外围设备;周边设备 :::
CPU 基础知识:核心数、频率、制造工艺和 Intel, Amd 版本
CPU 进阶知识:超线程、CPU 缓存、TDP(散热设计功耗)
CPU 工作简介:
The CPU has its own small workspace, consisting of several registers, each of which can hold a number. One register holds the memory address of the next instruction, and the CPU uses this information to fetch the next instruction. After it fetches an instruction, the CPU stores the instruction in another register and updates the first register to the address of the next instruction.
数据在计算机中存储方式:
- everything stored in a computer is stored as a number. Numbers are stored as numbers. Characters, such as the alphabetical characters you use in a text document, are stored as numbers; each character has a numeric code. The instructions that a computer loads into its registers are stored as numbers; each instruction in the instruction set has a numeric code.
- computer programs ultimately have to be expressed in this numeric instruction code, or what is called machine language.
High-level Computer Languages and Compilers
出现原因:
- you don’t have to express your instructions in a numeric code
- the instructions you use are much closer to how you might think about a problem than they are to the detailed approach a computer uses(重心放在解决问题角度而不是机器实现方式上)
编译器出现原因:高级语言机器看不懂!因此需要中间翻译官出现,将高级语言转换为机器语言。
The compiler is a program that translates the high-level language program into the detailed set of machine language instructions the computer requires. The compiler approach has another benefit. In general, each computer design has its own unique machine language(例如当前 ARM 架构的 M1 芯片和 Intel 的 x86 无法兼容)But you can match a compiler to a particular machine language. Therefore, with the right compiler or set of compilers, you can convert the same high-level language program to a variety of different machine-language programs.(也就是只管代码上的实现,各种平台电脑上有对应版本的编译器帮你实现你的代码在其上可以编译运行)
Language Standards
Time | Standard | Events |
---|---|---|
1978 | K&R C or Classic C |
The first edition of The C Programming Language by Brian Kernighan and Dennis Ritchie (1978), but it did not define the C library |
1989 | ANSI C/C89 | the American National Standards Institute (ANSI) established a committee (X3J11) in 1983 to develop a new standard. This standard (ANSI C) defined both the language and a standard C library. |
1990 | ISO C/C90 | The International Organization for Standardization adopted a C standard (ISO C) in 1990 |
1999 | C99 | 1. One of these main goals was to support international programming by, for example, providing ways to deal with international character sets. 1. A second goal was to “codify existing practice to address evident deficiencies.”(移植到 64位 处理器问题) 1. A third goal was to improve the suitability of C for doing critical numeric calculations for scientific and engineering projects, making C a more appealing alternative to FORTRAN. |
ANSI/ISO standard 规定精神:
- Trust the programmer.(太难了)
- Don’t prevent the programmer from doing what needs to be done.(好自由)
- Keep the language small and simple.(造轮子了解下?)
- Provide only one way to do an operation.(不太懂这个)
- Make it fast, even if it is not guaranteed to be portable.(为达到快,可以为特定机器量体裁衣而不考虑通用性)
Using C: Seven Steps
- Define the program objectives:考虑输入、处理逻辑、返回结果
- Design the program: Choosing a good way to represent the information can often make designing the program and processing the data much easier.
- Write the Code:考虑如何用代码实现。source code file contains the C rendition of your program design.
- Compile:源文件编译——目标文件——链接——可执行文件(任意过程报错编译终止)
- Run the Program:GUI操作系统直接双击/无GUI使用终端运行。
- Test and Debug the Program: 能编译运行只能说语法过关,但是输出结果不一定对,即程序有 bugs. Debugging is the process of finding and fixing program errors.
- Maintain and Modify the Program:开发后维护与更新,让你程序服务更多人 :::tips 初学者不要跳过第一二步,虽然简单的程序你很快能在脑海中想到目标代码,但是之后如果遇到大型项目,你这种脑海回想永远比不上纸上记笔记。好记性不如烂笔头,最终找 BUG 也好在文档中定位。
不要害怕犯错,失败乃成功之母。学习宗旨就是在写代码前一定要养成先计划的好习惯,而不是一上来就敲代码。 :::
Programming Mechanics
When you write a program in the C language, you store what you write in a text file called a source code file.
#include <stdio.h>
int main(void) {
printf("Concrete contains gravel and cement.\n");
return 0;
}
C implementations typically do this(convert your source code file to an executable file) in two steps: compiling and linking. The compiler converts your source code to an intermediate code(Object Code Files), and the linker combines this with other code to produce the executable file. C uses this two-part approach to facilitate the modularization of programs.
- You can compile individual modules separately and then use the linker to combine the compiled modules later. 单独修改一个文件而不是全盘修改
- The linker combines your program with precompiled library code.(可以直接使用预编译标准库)
Why the compiler converts source code to an intermediate code? And what is the Object Code Files?
It convert the source code to machine language code, placing the result in an object code file, or object file for short. (This assumes that your source code consists of a single file.) Although the object file contains machine language code, it is not ready to run.
The object file contains the translation of your source code, but it is not yet a complete program.
- The first element missing from the object code file is something called startup code, which is code that acts as an interface between your program and the operating system. 不同 OS 进程调度程序不同,因此计算使用相同的设备,它们之间的 startup code 也完全不同!
- The second missing element is the code for library routines. Nearly all C programs make use of routines (called functions ) that are part of the standard C library. 例如你的程序中调用
printf
函数,生成的目标文件中没有这个函数的机器代码实现,只存在一个想调用的请求。The actual code ofprintf
function is stored in another file, called a library. A library file contains object code for many functions.
What is the role of the linker?
It bring together these three elements—your object code, the standard startup code for your system, and the library code—and put them together into a single file, the executable file. For library code, the linker extracts only the code needed for the functions you use from the library
:::info
- An object file and an executable file both consist of machine language instructions.
- The object file contains the machine language translation only for the code you used
- The executable file also has machine code for the library routines you use and for the startup code. :::
常见编译器:
- The GNU Project, dating from 1987, is a mass collaboration that has developed a large body of free Unix-like software. (GNU stands for “GNU’s Not Unix.”) One of its products is the GNU Compiler Collection, or GCC, which includes the GCC C compiler. Its C compiler closely tracks changing C standards. Versions of GCC are available for a wide variety of hardware platforms and operating systems, including Unix, Linux, and Windows.
- The LLVM Project is an open-source collection of compiler-related software dating from a 2000 research project at the University of Illinois. Its Clang compiler processes C code and can be invoked as clang. Available on several platforms, including Linux, Clang became the default C compiler for FreeBSD in late 2012. Like GCC, Clang tracks the C standard pretty well.
Command-Line Compilers for the PC
如何在 Unix/Linux 平台上编写 C 程序?
Unix/Linux 平台上默认有编译器,但是文本编辑器(写代码)就没有 GUI,通常自带有 vi /vim 文本编辑器。 在 Unix/Linux 平台上开发 C 程序步骤(如右图) 1. 使用 Text Editor 编写你的 C 代码。 1. 在命令行中使用 cc (C Compiler 是编译器的别名,大多是使用 gcc )编译你的源程序,默认生成 a.out 可执行文件1. 运行 a.out 可执行文件。总结:Unix/Liux 上没有集成开发环境,大佬们通常都是配置 vi,把它打造成强大的编辑器! |
![]() |
---|---|
如何在 Windows 平台上编写 C 程序?
- 安装编译器:C compilers are not part of the standard Windows package, so you may need to obtain and install a C compiler.
- Cygwin runs in its own window, which has a Command-Prompt look but which imitates a Linux command-line environment.
- MinGW, on the other hand runs in the Windows Command-Prompt mode.(这个网上有很多教程)
文本编辑器:Source code files should be text files, not word processor files. (Word processor files contain a lot of additional information about fonts and formatting.)(也就是写代码的软件,例如 VS Code,它们只负责写代码,不负责编译。因此编写代码和编译是两码事,请记住 text editor 与 integrated development environments, IDEs 区别) :::info What’s the IDEs?
The key point is that each of these programs has a built-in editor you can use to write a C program.Each provides menus that enable you to name and save your source code file, as well as menus that allow you to compile and run your program without leaving the IDE.(将编写代码和编译运行一键完成)
- Each dumps you back into the editor if the compiler finds any errors, and each identifies the offending lines and matches them to the appropriate error messages.(智能纠错)
- 提供不同开发选项和环境,这对大工程项目非常重要(但是初学 C 语言没必要去使用 Visual Studio 这种大型集成开发环境,因为你的主要目标是学习 C 语法而不是学习如何使用 Visual Studio 软件)
Q:文本编辑器(Text Editor)和文字处理软件(Word)有什么区别?
简单来说就是文字效果,例如文字阴影、旋转效果等。Windows 的记事本就是一个纯文本编辑器,没有花里胡哨的文字效果。Word 就是专门排版文字,让整个布局好看,例如行/段间距这些都是纯文本编辑器做不到的。总之学编程就不要用 Word 这种写代码,用专门文本编辑器(Sublime Text, VS Code 等)
:::
如何在 Mac 平台上编写 C 程序?
Currently, Apple offers its Xcode development system as a free download. Xcode uses either the Clang or the GCC C compiler for C code. It used to use GCC by default, and now uses Clang by default. You can use Xcode settings to choose which compiler it uses and also which C standard to support. (Due to licensing matters, the version of Clang available with Xcode is more recent than the GCC version.)
Mac OS X is built on Unix, and the Terminal utility opens a window that lets you run programs in a Unix command-line environment. Apple doesn’t provide a command-line compiler as part of its standard package, but if you download Xcode, you can also download optional command-line tools that enable you to use the clang and the gcc commands to compile in command-line mode.
Summary
- C is a powerful, concise programming language. It is popular because it offers useful program-ming tools, good control over hardware, and because C programs are easier than most to transport from one system to another.
- C is a compiled language. C compilers and linkers are programs that convert C language source code into executable code.
- Programming in C can be taxing(US: [‘tæksɪŋ] UK: [‘tæksɪŋ] adj.繁重的;费力的;伤脑筋的), difficult, and frustrating, but it can also be intriguing, exciting, and satisfying. We hope you find it as enjoyable and fascinating as we do.
Review Questions
Q1: What does portability mean in the context of programming?
Q2: Explain the difference between a source code file, object code file, and executable file.
Q3: What are the seven major steps in programming?
Q4: What does a compiler do?
Q5: What does a linker do?
Programming Exercise
首先创建本章例题文件夹:
b07@SB:~$ mkdir CPrimerPlus && cd ./CPrimerPlus/
b07@SB:~/CPrimerPlus$ mkdir gettingReady
b07@SB:~/CPrimerPlus$ cd ./gettingReady/ && mkdir bin src obj include data
b07@SB:~/CPrimerPlus/gettingReady$ ls
bin data include obj src
Q1:You have just been employed by MacroMuscle, Inc. (Software for Hard Bodies). The company is entering the European market and wants a program that converts inches to centimeters (1 inch = 2.54 cm). The company wants the program set up so that it prompts the user to enter an inch value. Your assignment is to define the program objectives and to design the program (steps 1 and 2 of the programming process).
A1:题目让解决英寸与厘米单位进行转换,并且已经给出转换公式。由于数据中含有小数,因此选用 float
定义变量。
#inclde <stdio.h>
int main() {
float inches;
printf("Please input inches value: ");
scanf("%f", &inches);
float centimeters = 2.54 * inches;
printf("%.2f inches = %.2f centimeters\n", inches, centimeters);
return 0;
}
编译运行:
:::success
b07@SB:~/CPrimerPlus/gettingReady$ vi ./src/inches2centimeters.c
b07@SB:~/CPrimerPlus/gettingReady$ gcc -Wall ./src/inches2centimeters.c -o ./bin/inches2centimeters
b07@SB:~/CPrimerPlus/gettingReady$ ./bin/inches2centimeters
Please input inches value: 5
5.00 inches = 12.70 centimeters
:::