I want to call functions defined in test.c from other.c.
Can I extern
the function1
to call it? Also, do I have to use extern
in function2
and function3
, which are being called by function1
?
other.c
extern function1();
function1();
test.c
void function1()
{
function2();
function3();
}
void function2()
{
}
void function3()
{
}
Actually every function by default is extern :) - unless you declare them to be not :). It is enough if you have the prototype before the first call;
Function can be in the another .c file. You need to include the object file to the linking.
Function declarations are "by-default"
extern
.Quoting
C11
, chapter §6.2.2, (emphasis mine)So, you don't need to be explicit about it.
You need to compile the translation units aka source files (into object files) and then link them together to build the executable. That should do it.
You use
extern
to declare symbols which are external to the current translation unit (roughly a single source file with all its included header files).Simple example
The first source file
test1.c
Then the second source file
test2.c
:As you can see the function
function2
doesn't need anyextern
declaration anywhere. It is used only intest2.c
so onlyfunction1
needs to know about it.However in
test1.c
themain
function needs to know aboutfunction1
because it is called, then we make a forward declaration of the function prototype. This is done using theextern
keyword. But for declaring functions theextern
keyword isn't actually needed, as they are always considered "external" (as noted by Peter).extern
simply tells us that it is defined somewhere else. And you are using it in the file you are writing theextern
. But functions are by default extern. So you need not be explicit about it.