学会Linux下C语言编程--基础知识

http://tech.ddvip.com   2007年03月07日    社区交流

本文详细介绍学会Linux下C语言编程--基础知识

  前言:

  这篇文章介绍在LINUX下进行C语言编程所需要的基础知识.在这篇文章当中,我们将会学到以下内容:

  源程序编译

  Makefile的编写

  程序库的链接

  程序的调试

  头文件和系统求助

  1.源程序的编译

  在Linux下面,如果要编译一个C语言源程序,我们要使用GNU的gcc编译器. 下面我们以一个实例来说明如何使用gcc编译器.

  假设我们有下面一个非常简单的源程序(hello.c):

  int main(int argc,char **argv)
  {
  printf("Hello Linuxn");
  }

  要编译这个程序,我们只要在命令行下执行:

  gcc -o hello hello.c

  gcc 编译器就会为我们生成一个hello的可执行文件.执行./hello就可以看到程序的输出结果了.命令行中 gcc表示我们是用gcc来编译我们的源程序,-o 选项表示我们要求编译器给我们输出的可执行文件名为hello 而hello.c是我们的源程序文件.

  gcc编译器有许多选项,一般来说我们只要知道其中的几个就够了. -o选项我们已经知道了,表示我们要求输出的可执行文件名. -c选项表示我们只要求编译器输出目标代码,而不必要输出可执行文件. -g选项表示我们要求编译器在编译的时候提供我们以后对程序进行调试的信息.

  知道了这三个选项,我们就可以编译我们自己所写的简单的源程序了,如果你想要知道更多的选项,可以查看gcc的帮助文档,那里有着许多对其它选项的详细说明.

  2.Makefile的编写

  假设我们有下面这样的一个程序,源代码如下:

  /* main.c */
  #include "mytool1.h"
  #include "mytool2.h"
  int main(int argc,char **argv)
  {
  mytool1_print("hello");
  mytool2_print("hello");
  }
  /* mytool1.h */
  #ifndef _MYTOOL_1_H
  #define _MYTOOL_1_H
  void mytool1_print(char *print_str);
  #endif
  /* mytool1.c */
  #include "mytool1.h"
  void mytool1_print(char *print_str)
  {
  printf("This is mytool1 print %sn",print_str);
  }
  /* mytool2.h */
  #ifndef _MYTOOL_2_H
  #define _MYTOOL_2_H
  void mytool2_print(char *print_str);
  #endif
  /* mytool2.c */
  #include "mytool2.h"
  void mytool2_print(char *print_str)
  {
  printf("This is mytool2 print %sn",print_str);
  }

来源:linuxkit    作者:hoyt    责编:豆豆技术应用

正在加载评论...