#include <stdio.h>
void m();
void n() {
m();
}
void main() {
void m() {
printf("hi");
}
}
On compiling, an error
"undefined reference to m"
is shown. Which m
is being referred to?
#include <stdio.h>
void m();
void n() {
m();
}
void main() {
void m() {
printf("hi");
}
}
On compiling, an error
"undefined reference to m"
is shown. Which m
is being referred to?
As has been explained elsewhere, C doesn't support nested functions as a rule (gcc does as an extension, but almost no other compiler that I know of does).
You need to move the definition of m
outside of main
. Preferably you should define m
before it is used by n
:
#include <stdio.h>
void m()
{
printf("hi\n");
}
void n()
{
m();
}
int main( void ) // void main() is not a valid signature for main
{
n(); // call n, which calls m, which prints "hi"
return 0;
}
First, let me declare clearly,
OK, now, in your code,
m()
is a nested function insidemain()
. It is having block scope formain()
only. Outsidemain()
other functions cannot see the existence ofm()
,neither can callm()
directly.m()
can be called only insidemain()
.In your case, the call to
m()
insiden()
is causing the issue. Even if you provided the forward declaration asvoid m();
, linker won't be able to find the definition ofm()
and throw error.Solution: Move the definition of
m()
outsidemain()
, then you can use it from any other function.Also note, the recommended signature of
main()
isint main(void)
.