Reputation: 1194
this is a simple problem in c compiling and linking. But I want to discuss the principle of compiler and linker.
void f();
int main()
{
f();
}
this code receive error message "undefined reference to 'f()'"
int main()
{
f();
}
this code receive error message "f was not declared in this scope" what is the difference? and what 's more, the code
void f()
{
}
int main()
{
f();
}
runs well.
Upvotes: 0
Views: 1029
Reputation: 62
To clarify this question. You should know how the code becomes a executable program.
The first step is "Compile". Compile your source code into *.o file which is binary file.
The second if "Link". Combine your *.o file into executable file.
In your first example, you declare the function f
,but you don't define it. So when the Linker links the *.o file, it can't find function f
.
In your second example, you use function f
without declaration or implementation. So the Compiler report an error.
In your third example, the function f
implementation is ahead using it. It's right.
Upvotes: 0
Reputation: 6224
In the first case, you declare a function, but don't define it. It compiles properly, but doesn't link because there is no definition for f
. Hence the linker error.
In the second case, you attempt to call an undeclared symbol. The compiler doesn't know what f
is, so it issues an error. It's a different problem from a different stage of the compilation process, so the message is different.
In the third case, you have a well-defined program (except that main
fails to return a value). f
is both declared and defined. The program should compile, link, and execute properly.
Upvotes: 4