[cfe-dev] Clang Bug or Not-to-Spec C++ Question

Colin A. Smith colin at colinsmith.org
Wed Sep 15 19:03:36 PDT 2010


I found another case where clang doesn't work with a piece of code but gcc and Visual C++ do.

#include <iostream>
#include <string>

class foo {
public:
    foo(std::string string) : string_(string) {}
    friend inline std::ostream & operator<<(std::ostream & os, foo const & f) {
        os << f.string_;
        return os;
    }
private:
    std::string string_;
};

// commenting the next line out allows linking to work
std::ostream & operator<<(std::ostream & os, foo const & f);

int main(void) {
    foo f("Hello World!");
    std::cout << f << std::endl;
    return 0;
}

In this case, the error comes up at link time:

clang -lstdc++ inline_friend_test.cc 
/tmp/cc-D9nHGS.o: In function `main':
inline_friend_test.cc:(.text+0xb0): undefined reference to `operator<<(std::basic_ostream<char, std::char_traits<char> >&, foo const&)'
collect2: ld returned 1 exit status
clang: error: linker (via gcc) command failed with exit code 1 (use -v to see invocation)

It seems as if the operator declaration outside the class is making clang think the operator will be implemented elsewhere, ignoring the implementation inside the class declaration. As noted, removing the outside operator declaration allows everything to work, both with gcc and clang. The question is whether the outside operator declaration is against the C++ spec clang implements, or whether clang isn't dealing with it correctly.

Cheers.

-Colin



More information about the cfe-dev mailing list