C语言什么是外部函数?怎么⽤?

时间:2024-04-13 22:49:06

一、问题

        什么是外部函数呢?怎么使⽤?

二、解答

        外部函数在整个源程序中都有效,其定义的⼀般形式如下。

extern 类型声明符 函数名(形参表);

例如:

extern int f(int a,int b);

        调⽤外部函数时,需要对其进⾏声明。

[extern] 函数类型 函数名(参数类型表),函数名 2(参数类型表 2)…];

        如在函数定义中没有声明 extern 或 static,则隐含为 extern。在⼀个源⽂件的函数中调⽤其他源⽂件中定义的外部函数时,应⽤ extern 声明被调⽤函数为外部函数。

例如:

file1.c

main()
{
    extern int fl(int i);        /*外部函数声明,表⽰f1()函数在其他源⽂件中*/
}

file2.c

...
extern int fl(int i);        /*外部函数定义*/
{
    ...
}

⼜如:

f1.c

main()
{
    extern void input(...),process(...),output(...);
    input(...);
    process(...);
    output(...);
}

f2.c

...
extern void input(...)        /*定义外部函数*/
{
    ...
}        

f3.c

...
extern void process(...)        /*定义外部函数*/
{
    ...
}

f4.c

...
extern void output(...)        /*定义外部函数*/
{
    ...
}

三、总结

        外部函数是程序模块化的重要实现技术,⼀定要熟练掌握。