gpt4 book ai didi

c++ - constexpr 函数的 undefined symbol

转载 作者:IT老高 更新时间:2023-10-28 21:44:42 25 4
gpt4 key购买 nike

当我尝试编译以下代码时,出现链接器错误:Undefined symbols for architecture x86_64: "Foo()", referenced from: _main in main.o using LLVM 4.2。

此行为仅在函数标记为 constexpr 时发生。当函数被标记为 const 时,程序会正确编译和链接。为什么声明函数constexpr会导致链接器错误?

(我意识到以这种方式编写函数并没有带来编译时计算的好处;此时我很好奇为什么函数无法链接。)

ma​​in.cpp

#include <iostream>
#include "test.hpp"

int main()
{
int bar = Foo();
std::cout << bar << std::endl;

return 0;
}

test.hpp

constexpr int Foo();

test.cpp

#include "test.hpp"

constexpr int Foo()
{
return 42;
}

最佳答案

Why does declaring the function constexpr cause a linker error?

这是因为 constexpr 函数是隐式 inline 的。根据 C++11 标准的第 7.1.5/2 段:

A constexpr specifier used in the declaration of a function that is not a constructor declares that function to be a constexpr function. Similarly, a constexpr specifier used in a constructor declaration declares that constructor to be a constexpr constructor. constexpr functions and constexpr constructors are implicitly inline (7.1.2).

根据第 7.1.2/4 段,则:

An inline function shall be defined in every translation unit in which it is odr-used and shall have exactly the same definition in every case (3.2). [...]

关于c++ - constexpr 函数的 undefined symbol ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16219711/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com