Reputation: 21
I'm trying to call other adjacent functions (delay()
and delay_ex()
) from a function (bitcheck()
) as shown below and as expected, the compiler has thrown an error that delay()
and delay_ex()
functions weren't declared in the scope and I understood that we can't call functions other than from the main
. So, I declared these delay()
and delay_ex()
functions in a header file and called from this program by including the header file, it worked well. So, is there any other such way to make this work?
void bitcheck()
{
int i;
for(i=0;i<NELEMS(array); i++)
{
delay();
AP_CMU->DIVIDER = freq_def[0];
encryption(array,i);
delay();
// LCD_DisplayUint32(i,0,array[i]);
AP_CMU->DIVIDER = freq_def[6];
delay_ex(10);
decryption(intr_array,i);
delay_ex(10);
// LCD_DisplayUint32(i,10,array[i]);
}
}
void delay()
{
int i;
for (i = 0; i < 100000; i++) {
__NOP();
}
}
void delay_ex(int j)
{
for(int s=0; s < j; s++)
{
for ( int i = 0; i < 10000; i++) {
__NOP();
}
}
}
Upvotes: 0
Views: 164
Reputation: 386
You can write your functions above the code that calls them like:
void foo() {
}
void bar() {
}
int main () {
foo();
bar();
}
You can also forward declare functions like:
void foo();
void bar();
int main () {
foo();
bar();
}
void foo() {
}
void bar() {
}
Or you can put them in a header file and include it
file.h:
void foo();
void bar();
file.c:
#include "file.h"
int main () {
foo();
bar();
}
void foo() {
}
void bar() {
}
Upvotes: 4
Reputation: 93566
The compiler works in a single pass, as such when bitcheck()
is parsed, the signatures of delay()
and delay_ex()
are not known, so the compiler cannot verify the call is type-correct.
The rule is declare or define before use; there are two possible solutions:
bitcheck()
after the definition of delay()
and delay_ex()
delay()
and delay_ex()
.By declaring the functions in a header and including it before defining bitcheck()
, you used the second of these solutions, but use of an include file was not essential - #include
does noting more than insert the file content into the translation-unit prior to compilation. This is useful when the symbols will be called from a different translation-unit than that in which they are defined; if that is not intended the declarations may be written directly rather then #include
'd, and should also be declared static
to avoid external-linkage and potential name clashes with other translation-units.
Upvotes: 2
Reputation: 411
You need to define delay and delay_ex before bitcheck. Simply moving those two functions above bitcheck should suffice.
Upvotes: 0