1

I'm trying to compile this kind of code and I get link errors when trying to build using latest Xcode (6.0) on MacOSX Yosemite:

#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)

Note that the code compiles file using libstdc++:

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

OK
  • Does it work if you add an explicit call (`hello.size()`) somewhere? – molbdnilo Nov 06 '14 at 13:53
  • I just tested on Mavericks with XCode 6.1 and it works. Any reason why you do not update XCode? Maybe this has to do with clang version. – Christian Rapp Nov 06 '14 at 15:11
  • I confirm this. On Yosemite I reinstalled XCode 6.1 (remove & install again), installed command line tools 10.10 and it didn't help. More precisely, `hello.size()` started working, but `&std::string::size` still produces link error. – Anton Savin Nov 06 '14 at 18:32

1 Answers1

1

I was having the same problem. See Taking pointer to member std::string::size fails to link with libc++ but works with libstdc++

Basically the solution I came up with is to force the instantiation of the std::string template class.

Here is the proposed solution:

#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;
}
Community
  • 1
  • 1