Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Forward declaring a constexpr function in a header [duplicate]

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; 
}
like image 734
DeiDei Avatar asked Jan 27 '16 16:01

DeiDei


1 Answers

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.

like image 160
eerorika Avatar answered Sep 26 '22 00:09

eerorika