Reputation: 365
I am working on an embedded project and in the source code of the project (which is in C) contains a function which is used to check whether the ethernet type is polling or interrupt. We have a function as below
unsigned char mode(void);
unsigned char xmode(void)
{
if(mode())
return 1;
return 0;
}
The function mode() does not have a body. What will happen when the function mode() is called by the function xmode() ?
Upvotes: 2
Views: 565
Reputation: 62086
In the above code unsigned char mode(void);
tells the compiler that the function mode()
exist and it doesn't take any arguments but returns an unsigned char
.
This doesn't really define the function. It only defines the way to call it. This thing is called a function prototype
.
The function mode()
is defined either later in this same file or in another file (possibly an assembly file).
One of the common uses of function prototypes is to implement recursion.
Consider functions a()
and b()
, each calling the other one, and defined in the same file:
void a()
{
b();
}
void b()
{
a();
}
When the compiler sees b()
inside of a()
, it does not have a slightest idea of what b()
really is or what it's supposed to be. Obviously, if you change the order in which you define a()
and b()
, you will have the same problem, but now a()
won't be known inside of b()
.
To fix that, you add a prototype:
void b();
void a()
{
b();
}
void b()
{
a();
}
Now the compiler will know what b()
is (a function) and know how to call and use it.
Upvotes: 3
Reputation: 1856
To extend on the previous answers.
That isn't an "empty" function, it is a prototype.
The compiler uses this to output object code for the functions you have the body for. It needs to be able to set up the function call properly and make sure it handles any conversions and the like. The object code will contain references to the function and the linker will replace these references with the correct value.
It also means that the compiler can do error checking for you and get more information than the linker could. Fun fact, the C standard used to allow implicit declaration of functions.
(This is simplified, for clarity.)
Upvotes: 3
Reputation: 25073
This will either fail to link, or else there is a file that you're linking with that contains the actual mode()
function.
Upvotes: 2