M
mastermagrath
Hi,
I'm about half way through Bruce Eckels thinking in C++ Vol 1. He gives
a very short example of how compiler function name decoration helps
remove subtle bugs by type-safe linkage. However, upon looking at the
example i understand why it fails to link but don't understand why it
even compiles. Here's the code, which split between 2 files Def.cpp and
Use.cpp:
//File Def.cpp
//Function definition
void f(int) {}
In the second file, the function is misdeclared and then called:
//File Use.cpp
//Function misdeclaration
void f(char);
int main() {
f(1); // Causes a linker error
}
I thought that C++ forces the user to declare all functions before use
so it can perform compile time error checking e.g. against proper type
usage. In the above example i would have expected the compiler to throw
up an error because in creating the object file for Use.cpp it would
see that i declare a function that takes a char but actually call it
with an integer. However, it does compile, and only barfs during the
link stage as it can't find the function definition of the version that
takes a char argument.
Can anyone tell me why it compiles?
Also, as a side question i also thought C++ forces the user to define
function arguments with a variable name, but again in Def.cpp the
function is defined only with a variable type.
Thanks in advance
I'm about half way through Bruce Eckels thinking in C++ Vol 1. He gives
a very short example of how compiler function name decoration helps
remove subtle bugs by type-safe linkage. However, upon looking at the
example i understand why it fails to link but don't understand why it
even compiles. Here's the code, which split between 2 files Def.cpp and
Use.cpp:
//File Def.cpp
//Function definition
void f(int) {}
In the second file, the function is misdeclared and then called:
//File Use.cpp
//Function misdeclaration
void f(char);
int main() {
f(1); // Causes a linker error
}
I thought that C++ forces the user to declare all functions before use
so it can perform compile time error checking e.g. against proper type
usage. In the above example i would have expected the compiler to throw
up an error because in creating the object file for Use.cpp it would
see that i declare a function that takes a char but actually call it
with an integer. However, it does compile, and only barfs during the
link stage as it can't find the function definition of the version that
takes a char argument.
Can anyone tell me why it compiles?
Also, as a side question i also thought C++ forces the user to define
function arguments with a variable name, but again in Def.cpp the
function is defined only with a variable type.
Thanks in advance