免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1109 | 回复: 0
打印 上一主题 下一主题

linux下学习C编程 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2005-10-11 14:08 |只看该作者 |倒序浏览
刚开始学习在Linux下编程的一些记录。
  刚开始学习在Linux下编程的一些记录。(使用版本:Fedora core 4)
*****小例子*****
  这个小例子涉及到Linux下C的编写,编译,运行过程。
  
  代码编写(此例子借鉴于网上,能明白说明问题)
  /myfiles/Cprogram/c/main 下编写几个文件:main.c,mytool1.h,mytool1.c,mytool2.h,mytool2.c
  
     /*  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 %s
",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 %s
",print_str);
 }
编译过程
[root@localhost ~]# cd /myfiles
[root@localhost myfiles]# cd Cprogram
[root@localhost Cprogram]# cd c
       
       
       
       
       
        [root@localhost c]# cd main
[root@localhost main]# gcc -c main.c
[root@localhost main]# gcc -c mytool1.c
[root@localhost main]# gcc -c mytool2.c
[root@localhost main]# gcc -o main main.o mytool1.o mytool2.o
运行过程
[root@localhost main]# ./main
This is mytool1 print hello
This is mytool2 print hello
***** Makefile *****
像上面的例子一样,如果文件比较多,修改了一个文件的内容后,使用上面的编译过程需要重新写一遍,这是重复的工作。
使用Makefile文件来解决这个问题。
Makefile文件是一个编译命令的集合,但是并不是运行时都执行,而是修改了那一部分就重新编译有倚赖关系的文件。
下面是Makefile文件的书写规则:
target ... : prerequisites ...
            command
            ...
            ...
target也就是一个目标文件,可以是Object File,也可以是执行文件。
    prerequisites就是,要生成那个target所需要的文件或是目标。
    command也就是make需要执行的命令。(任意的Shell命令)
这是一个文件的依赖关系,也就是说,target这一个或多个的目标文件依赖于prerequisites中的文件,其生成规则定义在
command中。说白一点就是说,prerequisites中如果有一个以上的文件比target文件要新的话,command所定义的命令就会被执
行。这就是Makefile的规则。也就是Makefile中最核心的内容。
command前是一个TAB键。【如果没有TAB的话,运行时会出错,提示消息为:Makefile:2: *** 遗漏分隔符 。 停止。】
上面程序的Makefile文件可以写为:
main:main.o mytool1.o mytool2.o
    gcc -o main main.o mytool1.o mytool2.o
main.o:main.c mytool1.h mytool2.h
    gcc -c main.c
mytool1.o:mytool1.c mytool1.h
    gcc -c mytool1.c
mytool2.o:mytool2.c mytool2.h
    gcc -c mytool2.c
main是目标文件,冒号后面的main.o,mytool1.o,mytool2.o是他的依赖文件。
如果这三个文件有变动,就会执行下面的命令:gcc -o main main.o mytool1.o mytool2.o。下面几行也是类似的功能。
Makefile文件编写好以后,放在于源文件同一位置下,使用make命令即可执行。


本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u/10724/showart_51439.html
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP