zoukankan      html  css  js  c++  java
  • linux GCC编译C程序的问题

    今天下午突然觉得C里面有个地方比较模糊,一种莫名的恐惧产生,如是做两个实验

    有三个文件hello.c , hello.h, main.c

    代码如下:

    文件hello.h

    #include<stdio.h>
    int sayhello(char* str)
    {
     printf("%s \n",str);
     return 0;
    }
    这个里面申明并定义了一个函数sayhello

    文件hello.c

    #include<stdio.h>
    int sayhello(char* str)
    {
     printf("%s \n",str);
     return 0;
    }
    内容和hello.h一样,也是定一个函数sayhello

    文件main.c

    #include<stdio.h>
    #include"hello.h"
    int main(void)
    {
     char * str="hello";
     sayhello(str);
     return 0;
    }

    下面是编译测试(一):guoyuanwei@ubuntu:~/文档$ gcc -Wall main.c  hello.c -o hello
    main.c: In function ‘main’:
    main.c:5: warning: implicit declaration of function ‘sayhello’

    显示1个警告,隐式定义了函数sayhello,但能正确运行。

    测试(二):guoyuanwei@ubuntu:~/文档$ gcc -Wall main.c  hello.h -o hello
    main.c: In function ‘main’:
    main.c:5: warning: implicit declaration of function ‘sayhello’
    /tmp/cc3NGyXC.o: In function `main':
    main.c:(.text+0x1d): undefined reference to `sayhello'
    collect2: ld returned 1 exit status

    有个错误,意思是main.c中的函数sayhello没有定义,但是hello.h和hello.c的内容所完全一样的,实验一中却没有,这是为什么?

    测试(三):首先将main.c文件改为:也就是加上一个头文件。

    #include<stdio.h>
    #include"hello.h"
    int main(void)
    {
     char * str="hello";
     sayhello(str);
     return 0;
    }

    编译:guoyuanwei@ubuntu:~/文档$ gcc -Wall main.c -o hello
    一个错误和警告都没有,这是因为GCC在编译C源文件的时候,会根据#include包含相应的内容进来
    但是实验一、二就比较诡异了,难道GCC编译的时候,对hello.h和hello.c处理方式不一样?自动抛弃了hello.h文件,是不是只要.h的头文件都不会编译进来。GCC编译文件的时候难道看的是文件的后缀名而不是文件的内容吗?

  • 相关阅读:
    初遇黑客
    第四周学习总结
    第三周学习总结
    关于base64编码的原理及如何在python中实现
    在python中如何将十进制小数转换成二进制
    《信息安全专业导论》第二周学习总结
    计算机科学概论速读问题
    刘谨铭的自我介绍
    师生关系
    20201318快速浏览教材提问
  • 原文地址:https://www.cnblogs.com/guoyuanwei/p/2469927.html
Copyright © 2011-2022 走看看