Why does clang cause an error?

There are 3 files:

MyClass.h:

#ifndef LABEL
#define LABEL

class MyClass {
public:
    std::string toStr() const;
    friend std::ostream& operator << (std::ostream&, const MyClass&);
};

#endif

MyClass.cpp:

#include <string>
#include "MyClass.h"

std::string MyClass::toStr() const {
    std::string str = "some text";
    return str;
}

std::ostream& operator << (std::ostream& os, const MyClass& obj) {
    return os << obj.toStr();
}

main.cpp:

#include <iostream>
#include "MyClass.h"

int main() {
    MyClass a;
    std::cout << a << std::endl;
    return 0;
}

Compiling with GCC 5.1 ( g++-5 main.cpp BigInteger.cpp -std=c++11) does not cause errors, but when compiling with clang ( clang++ main.cpp BigInteger.cpp -std=c++11), the following error occurs:

Undefined symbols for architecture x86_64:
  "std::__1::basic_ostream<char, std::__1::char_traits<char> >& std::__1::operator<<<char, std::__1::char_traits<char>, std::__1::allocator<char> >(std::__1::basic_ostream<char, std::__1::char_traits<char> >&, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&)", referenced from:
      operator<<(std::__1::basic_ostream<char, std::__1::char_traits<char> >&, MyClass const&) in BigInteger-a5ec56.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

What's wrong?

PS OS X Yosemite. Clang Version:

Apple LLVM version 6.1.0 (clang-602.0.53) (based on LLVM 3.6.0svn)
Target: x86_64-apple-darwin14.3.0
Thread model: posix
+4
source share
1 answer

You need to include <iostream>and <string>inMyClass.h

Currently, the compiler does not know the meaning of std::ostream, <<and std::string.

0
source

All Articles