【问题标题】:Why does this C++ program compile on MacOS but not Ubuntu?为什么这个 C++ 程序在 MacOS 上编译而不是在 Ubuntu 上编译?
【发布时间】:2020-02-28 08:39:13
【问题描述】:

我在 Ubuntu 和 MacOS 机器上使用 Clang 版本 10:

ubuntu $ clang++ --version
clang version 10.0.0-++20200227124856+593a0dda7a6-1~exp1~20200227115450.103
Target: x86_64-pc-linux-gnu
Thread model: posix
InstalledDir: /usr/bin
osx $ clang++ --version
Apple LLVM version 10.0.1 (clang-1001.0.46.4)
Target: x86_64-apple-darwin18.7.0
Thread model: posix
InstalledDir: /Library/Developer/CommandLineTools/usr/bin

以下简单程序无法在 Ubuntu (16.04) 上编译,但可以在 MacOS 10.14 上编译:

// test.cpp

#include <atomic>
struct foo {

  bool bar;
  int baz;
  foo(bool bar, int baz) : bar(bar), baz(baz) {
  }
};

int main(int argc, char* argv[]) {
  std::atomic<foo> test_struct({false, 0});
  test_struct.load();

  return 0;
}

我正在编译

clang++ -std=c++14 test.cpp -o test

Ubuntu 上的错误是

In file included from test.cpp:1:
/usr/bin/../lib/gcc/x86_64-linux-gnu/5.4.0/../../../../include/c++/5.4.0/atomic:234:13: error: no matching constructor for initialization of 'foo'
        _Tp tmp;
            ^
test.cpp:13:11: note: in instantiation of member function 'std::atomic<foo>::load' requested here
  test_struct.load();
          ^
test.cpp:2:8: note: candidate constructor (the implicit copy constructor) not viable: requires 1 argument, but 0 were provided
struct foo {
       ^
test.cpp:2:8: note: candidate constructor (the implicit move constructor) not viable: requires 1 argument, but 0 were provided
test.cpp:6:3: note: candidate constructor not viable: requires 2 arguments, but 0 were provided
  foo(bool bar, bool baz) :
  ^
1 error generated.

我在这里遇到了一些未定义的行为吗?或者我需要采取什么措施才能使这两种情况完全相等?

编辑我可以通过向类型添加默认构造函数来编译它。但是我无法从std::atomics documentation 解析这个要求,我很困惑为什么默认构造函数似乎是在 MacOS 上生成而不是在 Ubuntu 上生成的。

【问题讨论】:

  • 我收到error: ‘proceed’ was not declared in this scope。那是minimal reproducible example吗?
  • 在 Ubuntu 中,您似乎拥有旧版本的库。参见例如clang 9gcc 5.4.
  • @oarfish 在 ubuntu clang 上默认链接 libstdc++,这是 GNU 对 C++ 标准库的实现。您需要采取额外的步骤才能链接到 libc++,这是 llvm 的 C++ 标准库。 libcxx.llvm.org/docs/UsingLibcxx.html
  • 是的,如果你想链接到 libstdc++,你需要升级它。您可以回答自己的问题,这样它就不会保持开放状态。
  • @oarfish 不用担心。如果您找到答案,我们鼓励您回答您自己的问题。

标签: c++ macos ubuntu default-constructor


【解决方案1】:

答案是在 Linux 系统上,clang 链接到 GNU C++ 标准库实现 libstc++,在这种情况下,它太旧(版本 5.4。或类似版本)并且不适用于所选的语言标准(c++14)。

有两种解决方案:

  1. 不知何故安装更新的libstdc++,它可能在也可能不在 Ubuntu 版本的 APT 软件包存储库中(在我的情况下没有更新版本)
  2. 使clang 使用LLVM 实现libc++。确保安装了最新版本(包libc++-dev)并在编译期间传递-stdlib=libc++

【讨论】:

    猜你喜欢
    • 2012-11-18
    • 1970-01-01
    • 1970-01-01
    • 2021-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-17
    相关资源
    最近更新 更多