[英]Why does g++ 10.1 complain about a named lambda in a header file and others do not?
I have a header file with a named lambda that I use for measuring the execution time of some functions (the lambda is partially a result of this question How to Write a Lambda Wrapping a Function with Optional Return Value ). 它位于一个 header 文件中,我从多个翻译单元中包含该文件。 这与 g++ 8 和 g++ 9 效果很好。现在,当我切换到 g++ 10.1 时,我在链接时出现错误。
请检查以下简化示例。
这是 Wandbox 中的示例: https://wandbox.org/permlink/Sizb6txrkW5dkJwT 。
文件“Lambda.h”:
#pragma once
#include <string>
auto measure = [](bool enabled, const std::string& taskName, auto&& function,
auto&&... parameters) -> decltype(auto)
{
return std::forward<decltype(function)>(function)(
std::forward<decltype(parameters)>(parameters)...);
};
文件“Test1.cpp”:
#include "Lambda.h"
文件“Test2.cpp”:
#include "Lambda.h"
然后我像这样构建:
g++ -c Test1.cpp
g++ -c Test2.cpp
g++ -shared -o Test.dll Test1.o Test2.o
在 g++ 9.2 之前一切正常,但在 g++ 10.1 中,我收到以下错误消息:
ld.exe: Test2.o:Test2.cpp:(.bss+0x0): multiple definition of `measure'; Test1.o:Test1.cpp:(.bss+0x0): first defined here
collect2.exe: error: ld returned 1 exit status
为什么? 如何使用 g++ 10.1 编译我的项目? I use the named lambda like I would use a template function, therefore I need to write my named lambda into a header file to be able to use it anywhere in the project and I cannot somehow separate declaration from definition, right?
我期待着一个答案!
链接时出现错误。
为什么?
因为您通过多次定义变量违反了单一定义规则。
而其他人没有?
为什么?
¯\_(ツ)_/¯ 不需要语言实现来诊断 ODR 违规。
I use the named lambda like I would use a template function, therefore I need to write my named lambda into a header file to be able to use it anywhere in the project and I cannot somehow separate declaration from definition, right?
正确的。
如何使用 g++ 10.1 编译我的项目?
简单的解决方案:声明变量inline
(C++17 特性)。
很简单,但每个 TU 都有自己的实例,但有一些奇怪的细节:声明变量static
。
第三种解决方案: lambda 什么都没有捕获,因此您不妨定义一个模板 function 代替。
第四种解决方案:不要将 lambda 存储为全局变量,而是编写一个返回 lambda 实例的内联 function。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.