As per this SO answer, modern compilers just do a single pass. Assuming GCC to be a modern one, why does the following simple program give me an error saying that test()
was not declared in this scope:
// Example program
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str="Naggy";
test(str);
cout<<str<<"\n";
}
void test(string& str) {
str="Rathore";
}
I know this error can be easily resolved by having a function prototype for test()
above main()
; or by declaring and defining test()
before main()
. However, I am not asking for a workaround - I am asking why does the compiler not detect that I have declared and defined test()
at a later stage in the program?
From what I remember from having learnt in school, many assemblers parse the input code twice; but if GCC (and maybe its assembler?) does that only once, then why doesn't it take such forward references into account? Or, am I missing something?
Thanks.
Note: cpp.sh does use GCC as noted here.
Edit: As per C++ rules, we need to declare the stuff before we use it. If (and when) the assembler does pass 1, does it not find out (and make a note) of the stuff that has been declared (like test()
in this case) and then use that later in pass 2 to to resolve the apparent forward references? Or, does this responsibility NOT lie with the assembler?