Linker error - Undefined symbols std::string::c_str() const on macos with libboost_thread?

微笑、不失礼 提交于 2019-12-05 09:28:56
T.C.

My psychic powers say:

  • g++ on your system is actually clang, configured to use libc++ by default. This is the usual configuration on Macs.
  • The homebrew boost distribution was compiled with libstdc++, and maybe the real g++.

The two standard libraries are not binary compatible, hence the linker error. To fix this, pass -stdlib=libstdc++ to your clang-in-g++'s clothing, or get the actual GCC (Homebrew should have a distribution), or build boost with libc++.

Repro & demo:

$ cat 1.cpp
#include <string>
#include <iostream>
int main() {
   std::string s("Blah");
   std::cout << s << std::endl;
}

$ g++ -v
Configured with: --prefix=/Applications/Xcode.app/Contents/Developer/usr --with-gxx-include-dir=/usr/include/c++/4.2.1
Apple LLVM version 5.1 (clang-503.0.40) (based on LLVM 3.4svn)
Target: x86_64-apple-darwin13.2.0
Thread model: posix
$ g++ 1.cpp -c -stdlib=libstdc++ -o 1.o
$ g++ 1.o -lstdc++
Undefined symbols for architecture x86_64:
  "std::allocator<char>::allocator()", referenced from:
      _main in 1.o
  "std::allocator<char>::~allocator()", referenced from:
      _main in 1.o
  "std::ostream::operator<<(std::ostream& (*)(std::ostream&))", referenced from:
      _main in 1.o
  "std::basic_string<char, std::char_traits<char>, std::allocator<char> >::basic_string(char const*, std::allocator<char> const&)", referenced from:
      _main in 1.o
  "std::basic_string<char, std::char_traits<char>, std::allocator<char> >::~basic_string()", referenced from:
      _main in 1.o
  "std::ios_base::Init::Init()", referenced from:
      ___cxx_global_var_init in 1.o
  "std::ios_base::Init::~Init()", referenced from:
      ___cxx_global_var_init in 1.o
  "std::cout", referenced from:
      _main in 1.o
  "std::basic_ostream<char, std::char_traits<char> >& std::endl<char, std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&)", referenced from:
      _main in 1.o
  "std::basic_ostream<char, std::char_traits<char> >& std::operator<<<char, std::char_traits<char>, std::allocator<char> >(std::basic_ostream<char, std::char_traits<char> >&, std::basic_string<char, std::char_traits<char>, std::allocator<char> > const&)", referenced from:
      _main in 1.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

$ g++ -stdlib=libstdc++ 1.o && ./a.out
Blah
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!