constexpr does not imply inline for non-static variables (C ++ 17 built-in variables)
Although constexpr implies inline for functions, it has no such effect for non-static variables, given C ++ 17 built-in variables.
For example, if you take the minimal example that I posted at: How do built-in variables work? and delete inline , leaving only constexpr , then the variable will get several addresses, which is the main thing to avoid built-in variables.
constexpr static variables are implicitly static.
Minimal example of what constexpr implies inline for functions
As mentioned at: https://stackoverflow.com/questions/106435/ ... the main effect of inline is not to embed, but to allow several function definitions, the standard quote is: How can a C ++ header file include an implementation?
We can observe this by playing the following example:
main.cpp
#include <cassert> #include "notmain.hpp" int main() { assert(shared_func() == notmain_func()); }
notmain.hpp
#ifndef NOTMAIN_HPP #define NOTMAIN_HPP inline int shared_func() { return 42; } int notmain_func(); #endif
notmain.cpp
#include "notmain.hpp" int notmain_func() { return shared_func(); }
Compile and run:
g++ -c -ggdb3 -O0 -Wall -Wextra -std=c++11 -pedantic-errors -o 'notmain.o' 'notmain.cpp' g++ -c -ggdb3 -O0 -Wall -Wextra -std=c++11 -pedantic-errors -o 'main.o' 'main.cpp' g++ -ggdb3 -O0 -Wall -Wextra -std=c++11 -pedantic-errors -o 'main.out' notmain.o main.o ./main.out
If we remove inline from shared_func , the link will fail with:
multiple definition of 'shared_func()'
because the header is included in multiple .cpp files.
But if we replace inline with constexpr , then it will work again, because constexpr also implies inline .
GCC implements this by marking characters as weak in ELF object files: How can a C ++ header file include an implementation?
Tested in GCC 8.3.0.