当我尝试编译以下代码时,出现链接器错误:Undefined symbols for architecture x86_64: "Foo()", referenced from: _main in main.o
using LLVM 4.2。
此行为仅在函数标记为 constexpr
时发生。当函数被标记为 const
时,程序会正确编译和链接。为什么声明函数constexpr
会导致链接器错误?
(我意识到以这种方式编写函数并没有带来编译时计算的好处;此时我很好奇为什么函数无法链接。)
main.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 aconstexpr
function. Similarly, aconstexpr
specifier used in a constructor declaration declares that constructor to be aconstexpr
constructor.constexpr
functions andconstexpr
constructors are implicitlyinline
(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/