5

Say I have the following files. Is this invalid C++ (linker chokes, so yeah) or is it a mistake in my syntax? Must a forward declaration of a constexpr function be in the same file as its definition?

header.h

extern constexpr int fun(int);

source.cpp

constexpr int fun(int x) 
{
    return x * 2; 
}
DeiDei
  • 10,205
  • 6
  • 55
  • 80

1 Answers1

16

It's wrong. constexpr implies that the function is inline. Inline functions must be defined in every translation unit where it's used. If you include that header in a translation unit other than source.cpp and use the function, that translation unit lacks the definition.

So, the solution is to move the implementation to the header. No need to worry about multiple definition, since the function is inline.

It doesn't technically need to be in the same file, but because the definition must be in every file that uses the function, it's simplest to define it in the same header.

eerorika
  • 232,697
  • 12
  • 197
  • 326