为什么此C ++程序在MacOS上而不在Ubuntu上编译?

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了为什么此C ++程序在MacOS上而不在Ubuntu上编译?相关的知识,希望对你有一定的参考价值。

我正在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.

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

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

答案

答案是,在Linux系统上,std::atomic链接到GNU C ++标准库实现clang,在这种情况下,该实现太旧(版本5.4或类似版本),并且不能与所选的语言标准一起使用( libstc++)。

有两种解决方案:

  1. 以某种方式安装更新的c++14,它可能会或可能不会存在于Ubuntu版本的APT软件包存储库中(在我的情况下,没有更新的版本)
  2. 使libstdc++使用LLVM实现clang。确保安装了最新版本(软件包libc++),并在编译过程中通过了libc++-dev

以上是关于为什么此C ++程序在MacOS上而不在Ubuntu上编译?的主要内容,如果未能解决你的问题,请参考以下文章

Valgrind 不能在 MacOS Mojave 上运行?与康达一起安装

在 C、MacOS 中播放哔声

Jni java启动器在c中工作,但不在c++中

应用程序在模拟器中运行但不在实时设备中请解决此问题[关闭]

python在调试模式下在c ++中工作,但不在exe文件中

为啥 ASP.NET-Core 应用程序会收到错误消息“此平台不支持锁定/解锁文件区域”。在 MacOS 上部署时?