升级到 Mac OS X 10.9/Xcode 5.0.1 后出现 C++ 链接错误

2022-01-11 00:00:00 linker c++ osx-mavericks clang++

升级到 Mac OS X 10.9/Xcode 5.0.1 后,创建共享库 (.dylib) 的命令行失败,出现多个未定义符号.

After upgrading to Mac OS X 10.9 / Xcode 5.0.1, command lines to create a shared library (.dylib) failed with several undefined symbols.

clang++ -dynamiclib -install_name test.dylib *.o -o test.dylib
Undefined symbols for architecture x86_64:
  "std::allocator<char>::allocator()", referenced from:
      _main in test.o
  "std::allocator<char>::~allocator()", referenced from:
      _main in test.o
  "std::ostream::operator<<(std::ostream& (*)(std::ostream&))", referenced from:
      _main in test.o
  "std::basic_string<char, std::char_traits<char>, std::allocator<char> >::basic_string(char const*, std::allocator<char> const&)", referenced from:
      _main in test.o
  "std::basic_string<char, std::char_traits<char>, std::allocator<char> >::~basic_string()", referenced from:
      _main in test.o
  "std::ios_base::Init::Init()", referenced from:
      ___cxx_global_var_init in test.o
  "std::ios_base::Init::~Init()", referenced from:
      ___cxx_global_var_init in test.o
  "std::cout", referenced from:
      _main in test.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 test.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 test.o
ld: symbol(s) not found for architecture x86_64

推荐答案

答案就在那里:https://mathematica.stackexchange.com/questions/34692/mathlink-linking-error-after-os-x-10-9-mavericks-upgrade

在 OS X 上有两种可用的标准 C++ 库实现:libstdc++ 和 libc++.它们不是二进制兼容的,libMLi3 需要 libstdc++.

There are two implementations of the standard C++ library available on OS X: libstdc++ and libc++. They are not binary compatible and libMLi3 requires libstdc++.

在 10.8 和更早版本上默认选择 libstdc++,在 10.9 上默认选择 libc++.为了保证与 libMLi3 的兼容性,我们需要手动选择 libstdc++.

On 10.8 and earlier libstdc++ is chosen by default, on 10.9 libc++ is chosen by default. To ensure compatibility with libMLi3, we need to choose libstdc++ manually.

为此,请将 -stdlib=libstdc++ 添加到链接命令中.

To do this, add -stdlib=libstdc++ to the linking command.

相关帖子:使用 Libc++ 未定义引用与 Clang 一起编译

编辑:经过一些调查,似乎 -mmacosx-version-min 和默认 libstd 的选择之间存在联系.如果最小版本 <10.9,则默认 libstd 等于 libstdc++,否则为 libc++.长期的解决方案显然是使用 -stdlib=libc++

Edit: After some investigations it seems there is a link between the -mmacosx-version-min and the choice of the default libstd. If min version < 10.9, then the default libstd is equal to libstdc++, else to libc++. The long term solution is clearly to use -stdlib=libc++

相关文章