constexpr: when to write "header-only" libraries?
Channel
C++ Weekly
Topics Apologies if my explanation is a bit confusing. Assume we have something like this as a setup for a project using an internal library:
MyLib.hpp // definitions
MyLib.cpp // implementation
main.cpp
Then, in main.cpp we include MyLib.hpp, and when compiling we produce MyLib.o and main.o and link them together.
This is a problem when we are trying to do constexpr code inside MyLib, since our main() code can't evaluate it at compile-time because it's a separate compiled object. That means that we can't really use any functions defined in MyLib as constexpr inside main (it's a compiler error).
The "alternative" (solution?) is to just make MyLib a "header-only" library and have all functions fully defined:
MyLib.hpp // both definition and implementation
main.cpp
Now when we include MyLib.hpp inside main, the compiler has access to all constexpr code and can perform compile-time evaluations. However, this has all the common drawbacks of increasing compile time for the bigger main.o object, and not working for dynamically linked libraries.
So, could you make a video covering what the "best practice" is for using constexpr inside libraries, and when to use a "header-only" approach? Does it depend on if the library is meant for internal use only or if you intend to publish it
Length
Probably 5-10 minutes
The solution to this problem is C++20 modules. Are you targeting any platforms that don't support that yet?
The solution to this problem is C++20 modules. Are you targeting any platforms that don't support that yet?
I've personally felt discouraged from using modules because of https://en.cppreference.com/w/cpp/compiler_support/20 still reporting GCC and Clang module support as "partial", although I must admit that I haven't done enough research to understand what exactly they mean by "partial", so it might not be a valid concern.
That being said, I still think that a video on this topic would be very informative for many people, even if it concludes with "the answer is modules!" like you did :)
Btw, still hoping for a video about modules :) #115