I’m trying to understand the relationship between compilation, linking, and the determination of constexpr values in C++. I know that constexpr values need to be fully resolved at compile-time, but some discussions suggest that these are determined during the entire translation process, which includes both compilation and linking. For instance, consider the following excerpt from “Effective Modern C++” book that has confused me:
“Conceptually, constexpr indicates a value that’s not only constant,
but is also known during compilation. Technically, their values are
determined during translation, and translation consists not just of
compilation but also of linking. Unless you write compilers or linkers
for C++, however, this has no effect on you, so you can blithely
program as if the values of constexpr objects were determined during
compilation.”
In my case, I wrote the following code in source.cpp:
#include <string_view>
constexpr std::string_view c = "Hello world";
constexpr std::string_view func()
{
return c;
}
In main.cpp, I attempted to use forward declarations for these constexpr values but encountered issues that prevented successful compilation.
#include <array>
#include <iostream>
#include <string_view>
constexpr std::string_view func();
int main()
{
constexpr std::string_view s = func();
constexpr size_t l = s.size();
std::array<int, l> arr;
std::cout << arr.size() << 'n';
}
Now I am confused based on what the book says and it seems to be in contrast with this example and the following errors:
main.cpp:10:22: Constexpr variable 'l' must be initialized by a
constant expression main.cpp:10:28: initializer of 's' is not a
constant expression main.cpp:9:33: declared here
but when i place all the code in main.cpp it compiles.