• 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编译文件的时候难道看的是文件的后缀名而不是文件的内容吗?

  • 相关阅读:
    (三)OpenCV-Python学习—图像平滑
    (二)OpenCV-Python学习—对比度增强
    (一)OpenCV-Python学习—基础知识
    mongodb的安装及使用
    python操作MySQL数据库的三个模块
    mysql数据库学习二
    (八)爬虫之js调试(登陆知乎)
    经典Paxos算法笔记
    ThreadPoolExecutor源码解读
    FutureTask源码解读
  • 原文地址:https://www.cnblogs.com/guoyuanwei/p/2469927.html
Copyright © 2020-2023  润新知