c++ - 为内联函数定义多次,怎么可能?

标签 c++ compiler-errors linker inline

下面引自 C++ primer 书的引述让我很困惑

Unlike other function, inline and constexpr functions may be defined multiple times in the program. After all, the compiler needs the definition, not just the declaration, in order to expand the code. However, all of the definitions of a given inline or constexpr must match exactly. As a result, inline and constexpr functions normally are defined in headers. -- C++ primer 5th Ed, 240 pp

“可能在程序中多次定义” 这句话让我很困惑。据我了解,声明可以多次进行,但定义只需要一次。

谁能给我一个例子,为什么会有多个定义。

最佳答案

在一个头文件中(我们称之为foo.h)你可以有

inline int foo() { /* do stuff */ }

现在,如果您将 foo.h 包含在几个 cpp 文件中,那么 foo 将在每个文件中定义,这将是一个多重定义错误。尽管 foo 被标记为 inline,但没关系,因为所有定义都是相同的。

As far as I understand, declaration can be made multiple time, but definition is only needed once

编译器在翻译单元(基本上是一个 cpp 文件)上工作,它可以在其中进行各种优化,但函数内联和 constexpr 要求编译器知道函数的定义。这意味着每个翻译单元都需要其中的函数定义。我们使用 inline 来确保这一点,否则会出现多重定义错误。

关于c++ - 为内联函数定义多次,怎么可能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53543479/

相关文章:

c++ - 具有不同内联函数定义的函数对象的实例化取决于链接顺序

haskell - ghc 编译的二进制文件是否需要 GHC 还是它们是独立的?

c++ - 我什么时候应该防止隐式破坏?它是如何工作的?

c++ - 由于段错误,我的程序在 fflush 上崩溃,...但并非总是如此?

java - 一般编程 (Java) 新手。我应该如何修复这些错误?嵌套的 if-else 结构的顺序是否正确?

C++编译错误LNK2019 : unresolved external symbol error

c++ - 将可执行文件与静态库的完整路径链接起来

c++ - 意外的 undefined reference

c++ - 如何使用模板 extern 关键字分隔测试类型?

linux - 编译后无法识别 gcc 7.1 参数