设置大 Eigen VectorXd 时出现 clang 错误

Getting clang error when setting large Eigen VectorXd

我有一个功能就是

Eigen::VectorXd x(%s);
x << %s;

其中第一个 %s 是大小,第二个是输入(动态设置我的向量)。当我 运行 在 "small" 输入(> 4000 个参数)时,一切正常。但是当我在较大的上进行时,我无法编译,我得到

clang: error: unable to execute command: Illegal instruction: 4
clang: error: clang frontend command failed due to signal (use -v to see invocation)
Apple LLVM version 10.0.1 (clang-1001.0.46.4)
Target: x86_64-apple-darwin18.6.0
Thread model: posix
InstalledDir: /Library/Developer/CommandLineTools/usr/bin
clang: note: diagnostic msg: PLEASE submit a bug report to http://developer.apple.com/bugreporter/ and include the crash backtrace, preprocessed source, and associated run script.
clang: note: diagnostic msg:
********************

PLEASE ATTACH THE FOLLOWING FILES TO THE BUG REPORT:
Preprocessed source(s) and associated run script(s) are located at:
clang: note: diagnostic msg: /var/folders/jc/nh9bfd2j5_q4w0x2mbq02svc0000gq/T/wenzel-f181fc.cpp
clang: note: diagnostic msg: /var/folders/jc/nh9bfd2j5_q4w0x2mbq02svc0000gq/T/wenzel-f181fc.sh
clang: note: diagnostic msg: Crash backtrace is located in
clang: note: diagnostic msg: /Users/ipq500/Library/Logs/DiagnosticReports/clang_<YYYY-MM-DD-HHMMSS>_<hostname>.crash
clang: note: diagnostic msg: (choose the .crash file that corresponds to your crash)
clang: note: diagnostic msg:

********************

我发现这可能是一个 XCode 问题,但想知道可能发生了什么。我在这里完全不知所措。

我假设你想做的是

Eigen::VectorXd x(4000);
x << 0, 1, 2, 3, /* many more values */ 3999;

这是通过重载 <<, 运算符实现的,即语法等同于:

operator,( /* many more calls ... */
  operator,(operator,(operator,(operator<<(x,0), 1), 2), 3)
           /* ... */, 3999 );

这对于编译器来说确实很难翻译,因为您有一个 4000 深度的调用堆栈(尽管这将被内联,但在编译时这可能会触发一些限制)。

对于 C++11 和开发分支,您可以尝试这个(不确定该语法的编译器限制):

Eigen::VectorXd x{ {0, 1, 2, 3, /* ... */ 3999} };

如果这不起作用,请尝试这个替代方案(C++03 兼容):

static const x_data[4000] = {0,1,2, /* ... */, 3999}; // ideally this should be aligned
Eigen::Map<Eigen::VectorXd> x(x_data, 4000);

或者,如果您有二进制形式的数据(例如,在单独的文件中),则在运行时 mmap 文件并在该数据上创建 Eigen::Map