使用vi编写HelloWorld.c程序,运行后,在控制台输出“Hello World!”
实现此案例需要按照如下步骤进行。
步骤一:打开vi,编辑源程序
代码如下:
#include <stdio.h> int main() { printf("Hello World!"); return 0; }
上述代码中,以下代码:
printf("Hello World!");
是在控制台上输出字符串“Hello World!”,其中printf是一个函数,用于将参数字符串输出到控制台上。
步骤二:预编译
在控制台使用gcc -E HelloWorld.c -o HelloWorld.i命令进行编译预处理,完成编译前的预处理工作,将源文件HelloWorld.c处理成HelloWorld.i文件。
步骤三:编译
在控制台使用gcc -S HelloWorld.i命令将与处理后的高级语言文件HelloWorld.i翻译成汇编语言,得到汇编文件HelloWorld.s。
步骤四:汇编
在控制台使用gcc -c HelloWorld.s命令将汇编文件HelloWorld.s翻译成机器指令,得到目标文件HelloWorld.o。
步骤五:链接
在控制台使用gcc HelloWorld.o -o HelloWorld命令将目标文件HelloWorld.o和标准库链接,得到可执行程序HelloWorld。
步骤六:运行
在控制台敲入可执行程序名HelloWorld,然后回车即可执行该文件。
本案例的完整代码如下所示:
#include <stdio.h> int main() { printf("Hello World!"); return 0; }
gcc是gnu旗舰产品,它的功能非常强大,有多达上千个选项用于完成各种功能。本案例介绍如何产生尽可能多的警告。
实现此案例需要按照如下步骤进行。
步骤一:使用Wall选项产生尽可能多的警告
在控制台使用gcc -Wall HelloWorld.c命令一次性编译链接源文件HelloWorld.c时,如果源文件有问题,则会产生尽可能多的警告,以提示程序的问题所在。
当需要编写较大型的程序时,往往把与这方面相关的函数集中到某一个文件中,把那方面相关的函数集中到另一个文件中。这时就需要将函数的声明放在扩展名为.h的头文件中,将函数的定义放在扩展名为.c的文件中,而在其他的扩展名为.c的文件中调用它们。
实现此案例需要按照如下步骤进行。
步骤一:定义头文件print.h
代码如下所示:
#ifndef exam_print_h #define exam_print_h void printArea(char* str, double area); #endif
上述代码中,以下代码:
#ifndef exam_print_h #define exam_print_h
和代码:
#endif
在一起的作用是防止该头文件中其间的内容被多次包含,而造成的重复定义错误。
上述代码中,以下代码:
void printArea(char* str, double area);
在头文件中声明了一个函数。
步骤二:在print.c文件中定义头文件print.h中声明的函数体
代码如下所示:
#include <stdio.h> #include "print.h" void printArea(char* str, double area) { printf("图形%s的面积是%lf\n", str, area); }
注意:需要使用#include将头文件包含进来。
上述代码中,以下代码:
void printArea(char* str, double area) { printf("图形%s的面积是%lf\n", str, area); }
是头文件print.h中声明的函数的定义。
步骤三:在main.c文件中调用头文件print.h中声明的函数
代码如下所示:
#include "print.h" int main(int argc, const char * argv[]) { // insert code here... printArea("圆", 100); return 0; }
注意:需要使用#include将头文件包含进来。
上述代码中,以下代码:
printArea("圆", 100);
是头文件print.h中声明的函数的调用。
步骤四:编译链接
在控制台使用gcc main.c print.c –I <指定路径>命令一次性编译链接源文件main.c和print.c,由于没有指定生成的文件名,所以生成可执行文件a.out。
上述命令中,选项-I的作用是先找-I指定的目录,再找当前目录,最后找系统目录。
本案例中的完整代码如下所示:
文件print.h
#ifndef exam_print_h #define exam_print_h void printArea(char* str, double area); #endif
文件print.c
#include <stdio.h> #include "print.h" void printArea(char* str, double area) { printf("图形%s的面积是%lf\n", str, area); }
文件main.c
#include "print.h" int main(int argc, const char * argv[]) { // insert code here... printArea("圆", 100); return 0; }
unix是一个多用户的操作系统,意味着每个用户登录系统之后,都有自己专用的运行环境。这个运行环境是由一组变量所定义,这组变量被称为环境变量。用户可以对自己的环境变量进行修改以达到对环境的要求。
本案例介绍如何添加头文件的附加搜索路径。
实现此案例需要按照如下步骤进行。
步骤一:头文件的附加搜索路径
在控制台上输入如下命令:
export C_INCLUDE_FILE=/Users/tarena/desktop
即可将C头文件的附加搜索路径设置为/Users/tarena/desktop,相当于gcc的-I选项的功能。