问题
glm has some code that looks like this, once pre-processor macros are resolved on my particular setup:
type_vec3.hpp
struct vec3
{
/*...*/
vec3& operator=(vec3 const & v);
/*...*/
}
type_vec3.inl
inline vec3& vec3::operator=(vec3 const & v)
{ /* implementation */ }
I couldn't find any related header include within the .inl file. When I try to rewrite with this kind of layout, I either get linker errors (which I believe is due to mismatch between header file declaration and the inline
-specified definition) or namespacing issues (if the header isn't included in the inl file).
Here is glm on GitHub: https://github.com/g-truc/glm. The files in question are here:
https://github.com/g-truc/glm/blob/master/glm/detail/type_vec3.hpp (L179)
https://github.com/g-truc/glm/blob/master/glm/detail/type_vec3.inl (L214)
The headers included in these two files are not present in the version of glm I'm using, which seems to behave fine.
Could someone please explain just what's going on here?
回答1:
This is just a way to split the implementation and the declaration into separate files. The .hpp
file declares vec3
, then #include
s the .inl
file (unless a non-inline version was requested). It's easy to miss the #include
as it is at the end of the .hpp
, but it is there. Despite the claim that the files are unconnected, they are connected, albeit in the opposite direction than was expected.
(Presumably, if GLM_EXTERNAL_TEMPLATE
is defined, the definition of vec3::operator=
would be provided in a separate component, not as an inline function.)
Another aspect worth noting is that these files are in a directory called "detail". That is a convention that says those files are subject to change without notice. In particular, they might not exist in older versions. (They also might not exist in newer versions, but that is more of an academic point when you are looking at the newest version.)
So the overall picture is that you #include
one of the normal header files, which will make sure both type_vec3.hpp
and type_vec3.inl
are #include
d in that order. That puts the inline definition in every translation unit that has the vec3
declaration.
来源:https://stackoverflow.com/questions/56844624/how-does-glm-get-away-with-not-declaring-a-function-inline-and-defining-it-inlin