为什么 g++ 10.1 抱怨头文件中的命名 lambda 而其他人没有?

Why does g++ 10.1 complain about a named lambda in a header file and others do not?

我有一个名为 lambda 的头文件,我用它来测量某些函数的执行时间(lambda 部分是这个问题的结果 )。它驻留在我从几个翻译单元中包含的头文件中。这在 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 编译我的项目?我像使用模板函数一样使用命名的 lambda,因此我需要将命名的 lambda 写入头文件,以便能够在项目的任何地方使用它,而且我不能以某种方式将声明与定义分开,对吗?

期待答案!

I get an error when linking.

Why?

因为您多次定义变量违反了一次定义规则。

and others do not?

Why?

¯\_(ツ)_/¯ 诊断 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?

没错。

How can I compile my project with g++ 10.1?

简单的解决方案:声明变量 inline(C++17 特性)。

很简单,但每个 TU 都有自己的实例的奇怪细节:声明变量 static

方案三:lambda什么都不捕获,不如自己定义一个模板函数。

第四种解决方案:不是将 lambda 存储为全局变量,而是编写一个内联函数,该函数 returns 是 lambda 的一个实例。