The friend function declared within the collaborative class, GCC does not compile

advertisements

I've got following code:

File: Foo.h

class Foo {
    friend void Bar();
};

File: Foo.cpp

void Bar() {};

File Test.cpp

#include "Foo.h"

int main(void) {
    Bar();
    return 0;
}

VS2008 compiles this without any error or warning. G++ 4.3.4 reports:

test.cpp: In function ‘int main()’:
test.cpp:8: error: ‘Bar’ was not declared in this scope

Why?


I found this question in the "unanswered" section, but the comments to the previous incorrect answer do constitute a correct answer. Therefore here is a community wiki response with that content.

Summary: GCC appears to be rejecting good code.

case when a friend function is defined (not only declared) inside class is covered by 11.4.5 ("A function can be defined in a friend declaration of a class if and only if the class is a non-local class, the function name is unqualified, and the function has namespace scope" -- your example fulfils these requirements). I guess that standard does allow declaration ("prototype") of a friend function inside class. It is the error g++ is generating which bothers me. – liori Nov 22 at 20:35

Also 11.4.3: "A function first declared in a friend declaration has external linkage (3.5). Otherwise, the function retains its previous linkage (7.1.1)." I think that seals the deal. – Potatoswatter 0 secs ago [delete this comment]