C语言中extern关键字的使用(引用其他文件中的变量或者函数)

C语言中extern关键字的使用(引用其他文件中的变量或者函数)


源码地址:码云地址

环境:linux,操作系统:Ubuntu 16.04

1.Linux下C程序的编辑,编译和运行以及调试。

很多人在学习编程语言的时候,习惯用IDE环境管理程序,比如vs2017,这样做很方便,用户只需要关注代码本身,但是对于一些简单的程序,可以直接用文本编辑器编辑,用编译命令进行编译,这样更有利于代码能力。
工具列表:
- 编辑:vim
- 编译和运行:gcc
- 调试:gdb

安装vim

sudo apt install vim

用vim编辑文件

在磁盘中新建第一个C文件:hello.c。
在该目录下打开命令行工具,输入:vim hello.c,进入vim一般模式,按下i进入编辑模式。
并输入以下代码:

#include <stdlib.h>
#include <stdio.h>
int main()
{
        char str[]="hello world!";
        printf("%s\n",str);
        return 0;

}

按下esc回到一般模式,并按::wq保存并推出文本编辑。

编译.c文件

在命令行中输入gcc hello.c -o hello,表示将hello.c文件编译后,生成名为hello的可执行文件。

执行

在命令行输入:./hello,输出:hello world!

2.extern 关键字的使用

现在在hello.c文件夹下再添加两个文件,分别命名为:hello.h,main.c。
hello.c,hello.h,main.c的内容分别为:

hello.c:
#include <stdio.h>
#include <stdlib.h>
#include "hello.h"
//函数的定义
char g_str[] = "hello world!";
void fun1()
{
    printf("%s\n", g_str);
}
hello.h:
#pragma once
#ifndef HELLOH
#define HELLOH
//将变量和函数声明为外部引用
extern char g_str[];
extern void fun1();
#endif
main.c:
#include <stdio.h>
#include <stdlib.h>
#include "hello.h"//包含头文件后,可以直接引用外部函数及变量
int main()
{
    fun1();
    //system("pause");
    return 0;
}

3.测试

将多个源文件编译为一个可执行文件,注意:本例中,main.c依赖于文件hello.c,所以要放在前面:gcc main.c hello.c -o main.
编译后将生成main可执行文件。
执行:./main,输出:hello world!.

猜你喜欢

转载自blog.csdn.net/wlfbitfc/article/details/81737099
今日推荐