function call not recognized as constexpr unless function definition is in same translation unit

Hi,

I have this definition in file a.cpp:

1
2
3
4
constexpr long fibonacci(long n)
{
	return n <= 2 ? 1 : fibonacci(n - 1) + fibonacci(n - 2);
}


and I try to use if in file b.cpp:

1
2
3
4
5
6
constexpr long fibonacci(long n);

void use_fibo()
{
      constexpr long l = fibonacci(13);
}


Compiling b.cpp gives this error:


expression did not evaluate to a constant


However if the function use_fibo() is placed in file a.cpp, after the definition of fibonacci, then it compiles perfectly.


This seems to indicate that in order to use constexpr functions in more than one translation unit, we need to place their definitions in header files with the inline option.


It does make some intuitive sense - the compiler needs to be sure the function is constexpr and will not accept our word for it. Is this why?

Regards,
Juan
This seems to indicate that in order to use constexpr functions in more than one translation unit, we need to place their definitions in header files with the inline option.

Yes, constexpr functions should be declared in a header if you plan on using them from multiple files but you don't need to use the inline keyword. constexpr functions are automatically inline.

It does make some intuitive sense - the compiler needs to be sure the function is constexpr and will not accept our word for it. Is this why?

When you use constexpr on a variable it means the compiler should know its value right there, at compile time, but that is not possible if the value comes from a function that has not been defined yet.
Last edited on
Thanks Peter87!
Topic archived. No new replies allowed.