c++ - constexpr 函数的 undefined symbol

标签 c++ c++11 linker-errors constexpr

当我尝试编译以下代码时,出现链接器错误: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/

相关文章:

c++ - 通过使用 fmt 库回退到指针来格式化类型

c++ - libc++ 的 std::basic_string 的 16 字节对齐模式背后的原因是什么?

java - Mac OS X 上的 JNI 链接时出现 undefined symbol 错误

ios - 编译器错误 - MultiTouchEvents 的 NSMutableDictionary

c - 链接器错误 "cannot find -l/some/path/libfilename"

c++ - 从 ASAN 获取新的删除类型不匹配

c++ - 我可以获取数组的最后一个元素的地址吗?

c++ - 如何循环 std::regex_search 的结果?

c++ - 如何保持在堆栈上分配的对象的动态类型?

c++ - 标准容器的类型特征?