使用libc ++访问Mac Yosemite上的std :: string成员时出现链接错误

时间:2014-11-06 13:41:19

标签: c++

我正在尝试编译这种代码,并且在尝试使用MacOSX Yosemite上的最新Xcode(6.0)进行构建时出现链接错误:

#include <iostream>
#include <string>

int main()
{
  auto x = &std::string::size;
  std::string hello("hello");
  std::cout << (hello.*x)() << std::endl;
  return 0;
}

$ g++ --std=c++11 -stdlib=libc++ hello.cpp -o hello     

KO:

Undefined symbols for architecture x86_64:

  "std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >::size() const", referenced from:
  _main in hello-a9a7cd.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

请注意,代码使用libstdc ++编译文件:

$  g++ --std=c++11 -stdlib=libstdc++ hello.cpp -o hello 

OK

1 个答案:

答案 0 :(得分:1)

我遇到了同样的问题。见Taking pointer to member std::string::size fails to link with libc++ but works with libstdc++

基本上我提出的解决方案是强制实例化std :: string模板类。

以下是建议的解决方案:

#include <iostream>
#include <string>

template class std::basic_string<char>;

int main()
{
  auto x = &std::string::size;
  std::string hello("hello");
  std::cout << (hello.*x)() << std::endl;
  return 0;
}