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);
return0;
}
按下esc回到⼀般模式,并按::wq保存并推出⽂本编辑。
编译.c⽂件
在命令⾏中输⼊gcc hello.c -o hello,表⽰将hello.c⽂件编译后,⽣成名为hello的可执⾏⽂件。
执⾏
在命令⾏输⼊:./hello,输出:hello world!
< 关键字的使⽤
现在在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!";c语言ide编辑器
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");
return0;
}
3.测试
将多个源⽂件编译为⼀个可执⾏⽂件,注意:本例中,main.c依赖于⽂件hello.c,所以要放在前⾯:gcc main.c hello.c -o main. 编译后将⽣成main可执⾏⽂件。
执⾏:./main,输出:hello world!.

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。