for a example consider the following two source files.
Code: Select all
#include <stdio.h>
extern void f1();
int main(int argc,char ** argv)
{
f1();
return 0;
}
Code: Select all
#include <stdio.h>
void f1()
{
printf ("f1() from file2\n");
return ;
}
Code: Select all
compile
#gcc -c file1.c file2.c
link
#gcc -o file file1.o file2.o
run
#./file
warning message like.
Code: Select all
file1.c: In function 'main':
file1.c:5: warning: implicit declaration of function 'f1'
Code: Select all
void f1();
However you still can omit 'extern' prefix keyword.
so for calling functions which are on other compilation units [which are declared in other source files and will be separately compiled and will built a '.o' file], it's not necessary to use 'extern' keyword.
So How 'extern' keyword is useful? why it exists?
As you already seen , to call external function you don't need to use 'extern' prefix. But when you referencing to a variable that exists outside your file scope without redefine it,you need to use 'extern' keyword.Such as like this.
Code: Select all
extern int error;
Code: Select all
int error;
So let's take a example. Review following two source files.
Code: Select all
#include <stdio.h>
extern int error;
int main(int argc,char **argv)
{
printf("error code is :%i\n",error);
return 0;
}
Code: Select all
int error =3;
... There are other uses of 'extern' keyword such as 'extern "C"' to call older C library functions within C++. And to call routines that are written in assembly language.
Good Clear Coding Style.
Although you don't need to explicitly use 'extern' as a prefix when you want to call a external function, ignoring it is not a good coding practice. believe me no industry expert is ignoring that, because you're writing code to human to read , lastly for the compiler. So I recommend you to explicitly put that prefix 'extern' where appropriate.
--Happy Coding--
--sandun--