有3个文件:
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;
}
使用GCC 5.1(g++-5 main.cpp BigInteger.cpp -std=c++11
)编译它们不会导致错误,但在使用clang(clang++ main.cpp BigInteger.cpp -std=c++11
)进行编译时会产生以下错误:
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)
出了什么问题?
P.S。 OS X Yosemite。铿锵版:
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