簡體   English   中英

為什么 g++ 10.1 抱怨 header 文件中的命名 lambda 而其他人沒有?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM