Undefined symbols for constexpr function
c++, c++11, constexpr, linker-errors
Solution
Why does declaring the function `constexpr` cause a linker error?
That is because `constexpr` functions are implicitly `inline`. Per Paragraph 7.1.5/2 of the C++11 Standard:
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).
Per Paragraph 7.1.2/4, then:
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). [...]
Problem
When I attempt compiling the following code I get a linker error: `Undefined symbols for architecture x86_64: "Foo()", referenced from: _main in main.o` using LLVM 4.2. This behavior only occurs when the function is marked `constexpr`. The program compiles and links correctly when the function is marked `const`. Why does declaring the function `constexpr` cause a linker error? (I realize that writing the function this way doesn't give the benefit of compile-time computation; at this point I am curious why the function fails to link.) 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; } ```